如果我有一個 TF 張量a = tf.Tensor([0, 2, 1, 7, 5, 6])。如何用另一個值替換超出特定范圍的元素?例如,我想用 -1 替換 < 1 或 > 6 的元素。所需的輸出是tf.Tensor([-1, 2, 1, -1, 5, 6])。
基本上做類似于a[(a>6) | (a<1)] = -1ifa是一個 numpy 陣列。當我嘗試運行它時,它拋出了錯誤TypeError: only integer scalar arrays can be converted to a scalar index
謝謝 :)
uj5u.com熱心網友回復:
它可以通過本機 TF 操作來完成。
import tensorflow as tf
a = tf.Variable([[0, 2, 1, 7, 5, 6]])
>> <tf.Variable 'Variable:0' shape=(1, 6) dtype=int32, numpy=array([[0, 2, 1, 7, 5, 6]])>
使用tf.where:
# Replace the elements that are < 1 or > 6 with -1.
a = tf.where(tf.less(a, 1), -1, a)
a = tf.where(tf.greater(a, 6), -1, a)
a
>> <tf.Tensor: shape=(1, 6), dtype=int32, numpy=array([[-1, 2, 1, -1, 5, 6]])>
或者在單行中,遵循相同的邏輯:
a = tf.where(tf.logical_or(tf.less(a, 1), tf.greater(a, 6)), -1, a)
a
>> <tf.Tensor: shape=(1, 6), dtype=int32, numpy=array([[-1, 2, 1, -1, 5, 6]])>
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/370279.html
上一篇:試圖將“形狀”轉換為張量但失敗
