感谢@Peter Hawkins 的出色回答。在许多情况下,需要额外的 reshape 步骤才能将 batch_size 添加为第一个维度。我添加了一个可选的额外步骤来重塑张量:
import tensorflow as tf
import numpy as np
batch_dependent_tensor = tf.placeholder(tf.float32, shape=[None, 3])
other_tensor = tf.constant([2, 3])
y = tf.tile(other_tensor, tf.shape(batch_dependent_tensor)[0:1])
# Reshaping the y tensor by adding the batch_size as the first dimension
new_shape = tf.concat([tf.shape(batch_dependent_tensor)[0:1], tf.shape(other_tensor)[0:1]], axis=0)
y_reshaped = tf.reshape(y, new_shape)
sess = tf.Session()
y_val, y_reshaped_val = sess.run([y, y_reshaped], feed_dict={batch_dependent_tensor: np.zeros([11, 3])})
print("y_val has shape %s, and value: %s" %(y_val.shape, y_val))
print("y_reshaped_val has shape %s, and value: %s" %(y_reshaped_val.shape, y_reshaped_val))
"""
# print output:
y_val has shape (22,), and value: [2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3 2 3]
y_reshaped_val has shape (11, 2), and value: [[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]
[2 3]]
"""
请注意,如果 other_tensor 的秩 > 1(它是矩阵或更高维度的张量),则需要对代码进行一些修改。