如何自定义Keras层的矩阵乘法

层结构:

  • 输入形状 (None,75)
  • 隐藏层1 – 形状为 (75,3)
  • 隐藏层2 – 形状为 (3,1)

对于最后一层,输出必须按以下方式计算 ( (H21*w1)*(H22*w2)*(H23*w3)),其中 H21,H22,H23 将是隐藏层2的输出,w1,w2,w3 将是不可训练的常数权重。那么如何为上述结果编写一个lambda函数呢?

def product(X):    return X[0]*X[1]keras_model = Sequential()keras_model.add(Dense(75, input_dim=75,activation='tanh',name="layer1" ))keras_model.add(Dense(3 ,activation='tanh',name="layer2" ))keras_model.add(Dense(1,name="layer3"))cross1=keras_model.add(Lambda(lambda x:product,output_shape=(1,1)))([layer2,layer3])print(cross1)        

NameError: name ‘layer2’ is not defined


回答:

使用功能API模型

inputs = Input((75,))                                         #形状 (batch, 75)output1 = Dense(75, activation='tanh',name="layer1" )(inputs) #形状 (batch, 75)output2 = Dense(3 ,activation='tanh',name="layer2" )(output1) #形状 (batch, 3)output3 = Dense(1,name="layer3")(output2)                     #形状 (batch, 1)cross1 = Lambda(lambda x: x[0] * x[1])([output2, output3])    #形状 (batch, 3)model = Model(inputs, cross1)

请注意,形状与您期望的完全不同。

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中创建了一个多类分类项目。该项目可以对…

发表回复

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