TypeError:添加的图层必须是类Layer

时间:2020-08-06 06:46:46

标签: python tensorflow keras

我正在尝试使用Keras进行二进制逻辑回归。但是我收到了typeError

TypeError: The added layer must be an instance of class Layer. Found: {<tensorflow.python.keras.layers.core.Dense object at 0x7f2887e399e8>}

这是我的标题:

import numpy as np 
import pandas as pd 
from keras.models import Sequential
from keras.layers import Dense
import keras.utils
#from tensorflow.keras import layers
from keras.optimizers import SGD
from keras import initializers

这是我的代码:

model=keras.Sequential({
    keras.layers.Dense(1,input_shape=(4,),activation='sigmoid',kernel_initializer='zeros',bias_initializer='zeros')
})
opt=SGD(learning_rate=0.05)
model.compile(optimizer=opt,loss='binary_crossentropy',metrics=['binary_accuracy'])

它显示的错误是:

TypeError                                 Traceback (most recent call last)
<ipython-input-4-50823f563eb6> in <module>()
      1 model=keras.Sequential({
----> 2     keras.layers.Dense(1,input_shape=(4,),activation='sigmoid',kernel_initializer='zeros',bias_initializer='zeros')
      3 })
      4 opt=SGD(learning_rate=0.05)
      5 model.compile(optimizer=opt,loss='binary_crossentropy',metrics=['binary_accuracy'])

3 frames
/usr/local/lib/python3.6/dist-packages/tensorflow/python/keras/engine/sequential.py in add(self, layer)
    180       raise TypeError('The added layer must be '
    181                       'an instance of class Layer. '
--> 182                       'Found: ' + str(layer))
    183 
    184     tf_utils.assert_no_legacy_layers([layer])

TypeError: The added layer must be an instance of class Layer. Found: {<tensorflow.python.keras.layers.core.Dense object at 0x7f2887e399e8>}

我发现奇怪的一件事是我能够更早地运行相同的代码,但现在却无法运行它,是否有我不熟悉的更新或代码错误?

1 个答案:

答案 0 :(得分:0)

尝试一下:

model=Sequential([
    Dense(1,input_shape=(4,),activation='sigmoid',kernel_initializer='zeros',bias_initializer='zeros')
])
opt=SGD(learning_rate=0.05)
model.compile(optimizer=opt,loss='binary_crossentropy',metrics=['binary_accuracy'])
model.summary()
Model: "sequential_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
dense_3 (Dense)              (None, 1)                 5         
=================================================================
Total params: 5
Trainable params: 5
Non-trainable params: 0