我的代码如下,
user_item_matrix = K.constant(user_item_matrix) # 输入变量 user_input = Input(shape=(1,), dtype='int32', name='user_input') item_input = Input(shape=(1,), dtype='int32', name='item_input') # 嵌入层 user_rating = Lambda(lambda x: tf.gather(user_item_matrix, tf.to_int32(x), axis=0))(user_input) item_rating = Lambda(lambda x: tf.gather(user_item_matrix, tf.to_int32(x), axis=1))(item_input)
其中user_item_matrix是一个6040*3706的矩阵。user_rating和item_rating的形状应该分别是(?, 3706)和(?, 6040)。然而,实际情况是:
user_rating: (?, 1, 3706)item_rating: (6040, ?, 1)
我对为什么6040出现在轴0而不是?(批量大小)感到困惑。我尝试使用Permute和Reshape来解决这个问题,但仍然没有效果。有没有好的解决方案来解决这样的问题?谢谢。
回答:
您可以查看关于tf.gather()
的文档:
生成一个输出张量,其形状为params.shape[:axis] + indices.shape + params.shape[axis + 1:]
您的params形状为(6040,3706)
,indices形状为(?,1)
。
因此,当设置axis=0
时,输出的形状为params.shape[:0] + indices.shape + params.shape[1:]
= () + (?,1) + (3706,)
。
当设置axis=1
时,输出的形状为params.shape[:1] + indices.shape + params.shape[2:]
= (6040,) + (?,1) + ()
。
您可以使用tf.transpose()
来重新排列轴。
import tensorflow as tfimport keras.backend as Kfrom keras.layers import Input,Lambdaimport numpy as npuser_item_matrix = K.constant(np.zeros(shape=(6040,3706)))# 输入变量user_input = Input(shape=(1,), dtype='int32', name='user_input')item_input = Input(shape=(1,), dtype='int32', name='item_input')# 嵌入层user_rating = Lambda(lambda x: tf.gather(user_item_matrix, tf.to_int32(x), axis=0))(K.squeeze(user_input,axis=1))item_rating = Lambda(lambda x: tf.transpose(tf.gather(user_item_matrix, tf.to_int32(x), axis=1),(1,0)))(K.squeeze(item_input,axis=1))print(user_rating.shape)print(item_rating.shape)# print(?, 3706)(?, 6040)