如何在Keras中重新排列张量的轴?

我的代码如下,

 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)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注