Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/tensorflow/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Keras:如何用Keras中的输入张量切片常数矩阵?_Python_Tensorflow_Keras - Fatal编程技术网

Python Keras:如何用Keras中的输入张量切片常数矩阵?

Python Keras:如何用Keras中的输入张量切片常数矩阵?,python,tensorflow,keras,Python,Tensorflow,Keras,代码如下: from keras.layers import Embedding, Input, Dense, Flatten, concatenate, Dot, Lambda from keras import backend as K def get_model(train, num_users, num_items, userlayers=[512, 64], itemlayers=[1024, 64]): num_layer = len(userlayers) # Numb

代码如下:

from keras.layers import Embedding, Input, Dense, Flatten, concatenate, Dot, Lambda
from keras import backend as K

def get_model(train, num_users, num_items, userlayers=[512, 64], itemlayers=[1024, 64]):
    num_layer = len(userlayers)  # Number of layers in the MLP

    # Input variables
    user_input = Input(shape=(1,), dtype='int32', name='user_input')
    item_input = Input(shape=(1,), dtype='int32', name='item_input')

    user_matrix = getTrainMatrix(train)
    user_latent_vector = K.variable(value=user_matrix[user_input, :])
    item_latent_vector = K.variable(value=user_matirx[:, item_input])

    userlayer = Dense(userlayers[0], activation="linear", name='userlayer0')
    itemlayer = Dense(itemlayers[0], activation="linear", name='itemlayer0')
    user_latent_vector = userlayer(user_latent_vector)
    item_latent_vector = itemlayer(item_latent_vector)

    prediction = Dot(1)([user_latent_vector, item_latent_vector])

    model_ = Model(inputs=[user_input, item_input], outputs=prediction)

    return model_
函数返回一个numpy矩阵,其中行表示用户,列表示项目。该矩阵应为常数矩阵,与
输入
张量无关。我想根据
输入
张量(小批量)得到一些行或列,即
用户输入
项目输入
,然后将切片送入MLP。我应该提前把numpy矩阵转换成张量吗?如何根据输入张量对矩阵进行切片


提前谢谢

是的,您应该将矩阵转换为张量,这可以很简单:

user_matrix = K.variable(user_matrix)
此外,还需要
K.gather
tf.gather
。tensorflow版本更好,因为您可以选择轴:

user_latent_vector = Lambda(lambda x: K.gather(user_matrix,x))(user_input)
item_latent_vector = Lambda(lambda x: tf.gather(user_matrix,x,axis=1))(item_input)

也许您需要
输入(batch_shape=(None,),…)
才能正确地实现这一点。

非常感谢!聚集函数非常有用,但使用它会导致另一个问题,即“AttributeError:'Tensor'对象没有属性'\u keras\u history'”。你知道怎么解决吗?@ZhihongDeng所有操作都必须在层内。更新了我的答案,将操作放在层内。感谢您的耐心等待。我尝试了Lambda层,但它引发了另一个错误,即“TypeError:传递给参数'Indexes'的值的数据类型float32不在允许值列表中:int32,int64”。这太奇怪了,因为没有任何东西被明确声明为浮点张量。我对它为什么说传递的索引参数具有浮点类型感到非常困惑。输入(索引)必须是整数,您可以使用
Input(…,dtype='int32')
。是的。我已强制输入张量和用户_矩阵为int32。我还发现解决这个问题的一种方法是使用
user\u潜伏因子=Lambda(Lambda x:tf.gather(user\u matrix,tf.to\u int32(x)))(user\u input)
,但这完全不是一种优雅的方法。