在张量流中找到所有特征的最大值
Find the max value across all features in tensorflow
考虑以下代码:
import tensorflow as tf
input_slice=3
labels_slice=2
def split_window(x):
inputs = tf.slice(x,[0], [input_slice])
labels = tf.slice(x,[input_slice], [labels_slice])
return inputs, labels
dataset = tf.data.Dataset.range(1, 25 + 1).batch(5).map(split_window)
for i, j in dataset:
print(i.numpy(),end="->")
print(j.numpy())
此代码将给我输出:
[1 2 3]->[4 5]
[6 7 8]->[ 9 10]
[11 12 13]->[14 15]
[16 17 18]->[19 20]
[21 22 23]->[24 25]
张量中的每一行 j
代表一个特征。我想找到所有功能的最大值。在这种情况下,它将是 25。我如何找到所有特征的最大值?
您的问题的一个解决方案是使用 tf.TensorArray
和 tf.reduce_max
:
import tensorflow as tf
input_slice=3
labels_slice=2
def split_window(x):
inputs = tf.slice(x,[0], [input_slice])
labels = tf.slice(x,[input_slice], [labels_slice])
return inputs, labels
dataset = tf.data.Dataset.range(1, 25 + 1).batch(5).map(split_window)
ta = tf.TensorArray(tf.int64, size=0, dynamic_size=True)
for i, j in dataset:
print(i.shape, i.numpy(),end="->")
print(j.numpy())
ta.write(ta.size(), j)
max_value = tf.reduce_max(ta.stack(), axis=(0, 1)).numpy()
print(max_value)
# 25
在 tf.reduce_max
中,您将获得维度 0 和维度 1 的最大值并减少张量。如果我没有正确理解问题,请随时提供一些反馈。
考虑以下代码:
import tensorflow as tf
input_slice=3
labels_slice=2
def split_window(x):
inputs = tf.slice(x,[0], [input_slice])
labels = tf.slice(x,[input_slice], [labels_slice])
return inputs, labels
dataset = tf.data.Dataset.range(1, 25 + 1).batch(5).map(split_window)
for i, j in dataset:
print(i.numpy(),end="->")
print(j.numpy())
此代码将给我输出:
[1 2 3]->[4 5]
[6 7 8]->[ 9 10]
[11 12 13]->[14 15]
[16 17 18]->[19 20]
[21 22 23]->[24 25]
张量中的每一行 j
代表一个特征。我想找到所有功能的最大值。在这种情况下,它将是 25。我如何找到所有特征的最大值?
您的问题的一个解决方案是使用 tf.TensorArray
和 tf.reduce_max
:
import tensorflow as tf
input_slice=3
labels_slice=2
def split_window(x):
inputs = tf.slice(x,[0], [input_slice])
labels = tf.slice(x,[input_slice], [labels_slice])
return inputs, labels
dataset = tf.data.Dataset.range(1, 25 + 1).batch(5).map(split_window)
ta = tf.TensorArray(tf.int64, size=0, dynamic_size=True)
for i, j in dataset:
print(i.shape, i.numpy(),end="->")
print(j.numpy())
ta.write(ta.size(), j)
max_value = tf.reduce_max(ta.stack(), axis=(0, 1)).numpy()
print(max_value)
# 25
在 tf.reduce_max
中,您将获得维度 0 和维度 1 的最大值并减少张量。如果我没有正确理解问题,请随时提供一些反馈。