【tensorflow】[Python] tensorflow tensor的批量条件改值 如何修改tensor中符合特定条件的元素值 将满足特定规则的tensor元素值修改

问题叙述

【tensorflow】[Python] tensorflow tensor的批量条件改值 如何修改tensor中符合特定条件的元素值 将满足特定规则的tensor元素值修改_第1张图片
这样一个tensor 想用类似

x[np.where(x > 8)] = 8
x[np.where(x<3)] = 3

的形式将其批量改成
【tensorflow】[Python] tensorflow tensor的批量条件改值 如何修改tensor中符合特定条件的元素值 将满足特定规则的tensor元素值修改_第2张图片
这种批量的条件判断改值,由于tensor不能直接用索引修改值
尝试了几种方法,
比如更改为Varient、numpy 等
会出现
TypeError: only integer scalar arrays can be converted to a scalar index
或者
TypeError: ‘ResourceVariable’ object does not support item assignment
等类似的错误

注:根据python版本和tf版本的不同,代码可能有错误或警告,请自行查询相应版本的解决方案。

2022/5/5 更新 ,感谢评论区@不啻逍遥然 的补充,tf版本不同会使得下面的解决方案可能不能正常运行。

tf2.x解决方案

import tensorflow as tf

tensor_input = tf.constant([i for i in range(20)], tf.float32)
tensor_input = tf.reshape(tensor_input, [4, 5])
print(tensor_input)
tensor_input = tf.where(tf.greater(tensor_input,8),8,tensor_input)
tensor_input = tf.where(tf.less(tensor_input,3),3,tensor_input)
print(tensor_input)

运行如下
【tensorflow】[Python] tensorflow tensor的批量条件改值 如何修改tensor中符合特定条件的元素值 将满足特定规则的tensor元素值修改_第3张图片

凌晨找到的解决方案,原理就查api吧 权当抛砖引玉

tf1.x解决方案

感谢评论区@不啻逍遥然 的补充
在tf1.x版本中,可以这样使用:

import tensorflow as tf
from tensorflow.keras import backend as K
import numpy as np

a = np.array([[1, 2, 3, 0],
[0, 2, 5, 15]])

b = tf.constant(a)
threshold = 2*tf.ones_like(b)
b = tf.where(tf.greater_equal(b, threshold), threshold, b)
print(K.eval(b))

你可能感兴趣的:(学习笔记,python,tensorflow)