Keras model.summary()说Valueerror:从未调用过此模型,

时间:2018-07-24 11:24:44

标签: machine-learning neural-network keras

这应该是非常简单的Keras程序。它一直工作到代码的最后一行。但是我称其为预测方法。当然,我使用了与训练数据相同的输入数据,但这没关系。

from keras.models import Sequential
import pandas as pd

url = 'https://raw.githubusercontent.com/werowe/logisticRegressionBestModel/master/KidCreative.csv'

data = pd.read_csv(url, delimiter=',')

labels=data['Buy']
features = data.iloc[:,2:16]

model = Sequential()
model.compile(optimizer='rmsprop' ,loss='binary_crossentropy',metrics=['accuracy'])
model.fit(data, labels, epochs=10, batch_size=32)
model.evaluate(labels, features, batch_size=128)
model.predict(labels)
model.summary()

但是我得到这个错误:

model.summary()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/walker/tf3/lib/python3.4/site-packages/keras/engine/network.py", line 1263, in summary
    'This model has never been called, this its weights '
ValueError: This model has never been called, this its weights have not yet been created, so no summary can be displayed. Build the model first (e.g. by calling it on some test data).

3 个答案:

答案 0 :(得分:5)

第一步应该是实际构建一个模型,您不需要这样做;即,在model = Sequential()之后,应该有一些model.add语句,以便在编译,拟合,将其用于评估或获取其摘要之前构建模型。

与其从一些模棱两可的质量仓库中获取指导​​,不如从官方示例和教程开始-例如在Keras MNIST CNN example上查找;在这里仅复制与模型相关的部分,我们得到:

model = Sequential()
# no model built, as in your case
model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

这应该已经给出了错误:

TypeError: Sequential model cannot be built: model is empty. Add some layers first.

很奇怪您没有举报您。

这是我们应该做的(同样,请参阅链接以获取完整详细信息):

model = Sequential()
model.add(Conv2D(32, kernel_size=(3, 3),
                 activation='relu',
                 input_shape=input_shape))
model.add(Conv2D(64, (3, 3), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.25))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss=keras.losses.categorical_crossentropy,
              optimizer=keras.optimizers.Adadelta(),
              metrics=['accuracy'])

model.summary()
# works OK

答案 1 :(得分:3)

正如@desertnaut所述,在调用mode.summary()之前,必须在模型中具有图层。

编辑:我想补充一点,即使您的模型具有模型层。如果第一层中没有“ input_shape”,summary()可能也不起作用。

因为在顺序模型中,使用前一层的输出尺寸来计算每层输入的尺寸(因此参数的数量),但是需要启动第一层的链输入尺寸。因此,没有输入维度就无法生成模型摘要。

注意:如果您未明确指定输入维,则keras会在您首次调用fit()时弄清楚它。因此,如果您未指定input_shape,则需要在model.summary()之前调用model.fit()

答案 2 :(得分:0)

感谢Matias Valdenegro,我添加了一些输入层并更改了损失函数。现在可行:

import tensorflow as tf
from keras.models import Sequential
import pandas as pd
from keras.layers import Dense

url = 'https://raw.githubusercontent.com/werowe/logisticRegressionBestModel/master/KidCreative.csv'

data = pd.read_csv(url, delimiter=',')

labels=data['Buy']
features = data.iloc[:,2:16]

model = Sequential()

model.add(Dense(units=64, activation='relu', input_dim=1))
model.add(Dense(units=14, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])

model.fit(labels, features,
          batch_size=12,
          epochs=10,
          verbose=1,
          validation_data=(labels, features))

model.evaluate(labels, features, verbose=0)

model.summary()