python - 编译加载模型时 Keras ValueError

标签 python tensorflow keras

我训练了以下网络并保存了它。编译重新加载的网络时,出现错误:

ValueError: Error when checkingModelTarget: expected dense_3 to haveFast (None, 1) but got array with shape (10000, 10)

可能是什么原因?许多类似问题的解决方案并没有真正帮助我。

代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Convolution2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_utils
from keras import backend as K
from keras.models import model_from_json

K.set_image_dim_ordering('th')

# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)

# load data
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# reshape to be [samples][pixels][width][height]
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28).astype('float32')

# normalize inputs from 0-255 to 0-1
X_train = X_train / 255
X_test = X_test / 255
# one hot encode outputs
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]

def larger_model():
    # create model
    model = Sequential()
    model.add(Convolution2D(30, 5, 5, border_mode='valid', input_shape=(1, 28, 28), activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Convolution2D(15, 3, 3, activation='relu'))
    model.add(MaxPooling2D(pool_size=(2, 2)))
    model.add(Dropout(0.2))
    model.add(Flatten())
    model.add(Dense(128, activation='relu'))
    model.add(Dense(50, activation='relu'))
    model.add(Dense(num_classes, activation='softmax'))
    # Compile model
    model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
    return model

# build the model
model = larger_model()
# Fit the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=1, batch_size=200, verbose=2)
# Final evaluation of the model
scores = model.evaluate(X_test, y_test, verbose=0)
print("Baseline Error: %.2f%%" % (100-scores[1]*100))


# save model and weights
print("Saving model...")
model_json = model.to_json()
with open('mnist_model.json', 'w') as json_file:
    json_file.write(model_json)
model.save_weights("mnist_weights.h5")
print("model saved to disk")

# load model and weights
print("Laoding model...")
with open('mnist_model.json') as json_file:
    model_json = json_file.read()

model = model_from_json(model_json)
model.load_weights('mnist_weights.h5')
print("mode loaded from disk")

print("compiling model...")
model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

scores = model.evaluate(X_test, y_test, verbose=0)
print("Baseline Error: %.2f%%" % (100-scores[1]*100))

最佳答案

为什么在加载模型后执行此操作? :

model.compile(loss='sparse_categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

您的基础模型使用 categorical_crossentropy,不同之处在于最新版本需要分类,一个热编码目标,而稀疏版本需要索引并调用 np.utils.to_categorical() 在后台。所以在这里,keras 提示因为你使用的是稀疏版本,它期望索引的形状是 (?, 1) 但你输入 y_test,编码为 one-hot形状 (?, 10)

解决方案,要么不改变损失类型,要么使用:

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

加载模型后,或者反转一个热编码的y_test:

y_test = np.argmax(y_test)

我希望这对您有所帮助:-)

关于python - 编译加载模型时 Keras ValueError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43199724/

相关文章:

python - 返回抓取的结果数

python - Pyinstaller - 转换为 .exe 的 python 脚本未按预期方式执行程序

Tensorflow:tf.nn.dropout 和 tf.contrib.rnn.DropoutWrapper 之间有什么区别?

react-native - React Native 适合使用 TensorFlow.js 构建的跨平台机器学习应用程序吗?

python - TensorFlow的conv2d如何跨越多个 channel ?

python - 这两种保存keras机器学习模型权重的方式有什么区别?

python - Talos 多 GPU 功能

tensorflow - 如何在keras中堆叠多个lstm?

python - 如何为 Pandas 多索引数据框中的每个子索引添加一行?

python - 如何将现有的 Django 应用程序转换为在 virtualenv 中运行?