我有一个简单的回归模型,如下所示。图层layer_abc
和layer_efg
都以(None, 5)
作为输出,因此它们的输出具有相同的尺寸并且可以添加。因此,我想取消隐藏代码#keras.layers.Add()(['layer_abc', 'layer_efg'])
。但是,每当执行此操作时,都会出现错误AttributeError: 'str' object has no attribute 'get_shape'
。如果我没有取消隐藏该行,那么代码很好。
如何在没有错误的情况下添加两层?非常感谢!
from __future__ import absolute_import, division, print_function
from scipy import misc
import tensorflow as tf
from tensorflow import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPooling2D, BatchNormalization, Activation
import numpy as np
import matplotlib.pyplot as plt
train_images=np.array([[[0],[1],[2]],[[0],[0],[2]],[[1],[1],[1]],[[1],[0],[1]]])
train_labels=np.array([[1],[0],[1],[0]])
model = keras.Sequential([
keras.layers.Flatten(input_shape=(3, 1)),
keras.layers.Dense(5, activation=tf.nn.relu,name='layer_abc'),
keras.layers.Dense(5, activation=tf.nn.relu,name='layer_efg'),
#keras.layers.Add()(['layer_abc', 'layer_efg']),
keras.layers.Dense(1, activation=tf.nn.softmax),
])
model.compile(optimizer='adam',
loss='mean_squared_error',
metrics=['accuracy','mean_squared_error'])
print(model.summary())
model.fit(train_images, train_labels, epochs=2)
答案 0 :(得分:1)
您可以像这样使用功能性API进行加,对于0到1之间的单个输出,对输出使用S型激活:
input = keras.layers.Input((3,1))
x1 = keras.layers.Dense(5, activation=tf.nn.relu, name='layer_abc')(input)
x2 = keras.layers.Dense(5, activation=tf.nn.relu, name='layer_efg')(input)
x = keras.layers.Add()([x1, x2])
x = keras.layers.Flatten()(x)
output = keras.layers.Dense(1, activation=tf.nn.sigmoid)(x)
model = keras.models.Model(input, output)
这可能有效:
model = keras.Sequential([
keras.layers.Flatten(input_shape=(3, 1)),
keras.layers.Dense(5, activation=tf.nn.relu,name='layer_abc'),
keras.layers.Dense(5, activation=tf.nn.relu,name='layer_efg')])
model.add(keras.layers.Lambda(lambda x: tf.add(model.layers[1].output, x)))
model.add(keras.layers.Dense(1, activation=tf.nn.sigmoid))