用于矩阵矢量乘法的Keras Lambda层 [英] Keras Lambda Layer for matrix vector multiplication

查看:207
本文介绍了用于矩阵矢量乘法的Keras Lambda层的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在keras中有一个lambda层来执行矢量矩阵乘法,然后再将其传递到另一层.矩阵是固定的(我不想学习).下面的代码:

I am trying to have a lambda layer in keras that performs a vector matrix multiplication, before passing it to another layer. The matrix is fixed (I don't want to learn it). Code below:

model.add(Dropout(0.1))    
model.add(Lambda(lambda x: x.dot(A)))
model.add(Dense(output_shape, activation='softmax'))
model.compile(<stuff here>)}

A是固定矩阵,我想做x.dot(A)

A is the fixed matrix, and I want to do x.dot(A)

运行此命令时,出现以下错误:

WHen I run this, I get the following error:

'Tensor' object has no attribute 'dot'

当我用matmul替换点时出现相同的错误(我正在使用tensorflow后端)

Same Error when I replace dot with matmul (I am using tensorflow backend)

最后,当我将lambda层替换为

Finally, when I replace the lambda layer by

model.add(Lambda(lambda x: x*A))

我收到以下错误:

model.add(Lambda(lambda x: x*G))

model.add(Dense(output_shape, activation='softmax'))

AttributeError: 'tuple' object has no attribute '_dims'

我是Keras的新手,所以我们将不胜感激.谢谢

I'm new to Keras so any help will be appreciated. Thanks

推荐答案

为lambda创建函数:

Create a function for the lambda:

import keras.backend as K
import numpy as np

numpyA = np.array(define A correctly here, with 2 dimensions)

def multA(x):
    A = K.variable(numpyA)

    return K.dot(x,A)

model.add(Lambda(multA))

这篇关于用于矩阵矢量乘法的Keras Lambda层的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆