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

问题叙述

在这里插入图片描述
这样一个tensor 想用类似

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

的形式将其批量改成
在这里插入图片描述
这种批量的条件判断改值,由于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)

运行如下
在这里插入图片描述

凌晨找到的解决方案,原理就查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))
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值