我正在努力解决一个问题,我需要转换我的张量,以便在总值中,最大值为 1,其余为 0。
tf.Tensor(
[[0.05]
[0.1]
[0.5]
[0.35]],shape=(4,1),dtype = float32)
我试过了
out = tf.sparse_to_dense(tf.argmax(a),tf.cast(tf.shape(a), dtype=tf.int64), tf.reduce_max(a))
但不幸的是,收到错误
Input must be a SparseTensor.
我希望输出为
tf.Tensor(
[[0]
[0]
[1]
[0]],shape=(4,1),dtype = float32)
请帮我解决问题。 多谢
尝试这样
x = tf.constant(
[[0.05],
[0.1],
[0.5],
[0.35]])
top_values, top_indices = tf.nn.top_k(tf.reshape(x, (-1,)), 1)
tf.cast(tf.greater_equal(x, top_values), tf.float64)
输出
<tf.Tensor: shape=(4, 1), dtype=float64, numpy=
array([[0.],
[0.],
[1.],
[0.]])>
Using keras 后端K.cast(K.equal(a, K.max(a)), dtype='int8')
import numpy as np
import tensorflow as tf
from tensorflow.keras import backend as K
a = np.arange(0, 1, 0.1)
a = a[:, np.newaxis]
a
array([[0. ],
[0.1],
[0.2],
[0.3],
[0.4],
[0.5],
[0.6],
[0.7],
[0.8],
[0.9]], dtype=float32)
tensor = K.cast(a, dtype='float32')
tensor
<tf.Tensor: shape=(10, 1), dtype=float32, numpy=
array([[0. ],
[0.1],
[0.2],
[0.3],
[0.4],
[0.5],
[0.6],
[0.7],
[0.8],
[0.9]], dtype=float32)>
K.cast(K.equal(a, K.max(a)), dtype='int8')
<tf.Tensor: shape=(10, 1), dtype=int8, numpy=
array([[0],
[0],
[0],
[0],
[0],
[0],
[0],
[0],
[0],
[1]], dtype=int8)>