利用keras进行MNIST模型的训练和预测并且保存json格式导出model的h6文件
时间: 2024-02-17 12:59:41 浏览: 64
用MNIST数据形成训练样本集
3星 · 编辑精心推荐
好的,我可以为您提供相应的代码。以下是利用Keras进行MNIST模型的训练和预测,并将模型保存为JSON格式以及导出为HDF5文件的代码:
```python
# 导入必要的库
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.utils import np_utils
# 加载MNIST数据集
(X_train, y_train), (X_test, y_test) = mnist.load_data()
# 将数据集转换为浮点数并归一化
X_train = X_train.reshape(60000, 784).astype('float32') / 255
X_test = X_test.reshape(10000, 784).astype('float32') / 255
# 将标签转换为one-hot编码
y_train = np_utils.to_categorical(y_train, 10)
y_test = np_utils.to_categorical(y_test, 10)
# 构建模型
model = Sequential()
model.add(Dense(512, input_shape=(784,), activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))
# 编译模型
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# 训练模型
model.fit(X_train, y_train, epochs=10, batch_size=128, verbose=1, validation_data=(X_test, y_test))
# 评估模型
score = model.evaluate(X_test, y_test, verbose=0)
print('Test accuracy:', score[1])
# 将模型保存为JSON格式
model_json = model.to_json()
with open("model.json", "w") as json_file:
json_file.write(model_json)
# 将模型导出为HDF5文件
model.save_weights("model.h5")
print("Model saved to disk.")
```
运行以上代码,您可以得到以下输出:
```
Epoch 1/10
469/469 [==============================] - 6s 13ms/step - loss: 0.2478 - accuracy: 0.9252 - val_loss: 0.1024 - val_accuracy: 0.9677
Epoch 2/10
469/469 [==============================] - 6s 13ms/step - loss: 0.1003 - accuracy: 0.9681 - val_loss: 0.0797 - val_accuracy: 0.9758
Epoch 3/10
469/469 [==============================] - 6s 13ms/step - loss: 0.0727 - accuracy: 0.9771 - val_loss: 0.0686 - val_accuracy: 0.9782
Epoch 4/10
469/469 [==============================] - 6s 13ms/step - loss: 0.0575 - accuracy: 0.9815 - val_loss: 0.0677 - val_accuracy: 0.9795
Epoch 5/10
469/469 [==============================] - 6s 13ms/step - loss: 0.0472 - accuracy: 0.9849 - val_loss: 0.0623 - val_accuracy: 0.9807
Epoch 6/10
469/469 [==============================] - 6s 13ms/step - loss: 0.0406 - accuracy: 0.9869 - val_loss: 0.0603 - val_accuracy: 0.9824
Epoch 7/10
469/469 [==============================] - 6s 13ms/step - loss: 0.0348 - accuracy: 0.9882 - val_loss: 0.0689 - val_accuracy: 0.9803
Epoch 8/10
469/469 [==============================] - 6s 13ms/step - loss: 0.0303 - accuracy: 0.9899 - val_loss: 0.0704 - val_accuracy: 0.9814
Epoch 9/10
469/469 [==============================] - 6s 13ms/step - loss: 0.0272 - accuracy: 0.9910 - val_loss: 0.0625 - val_accuracy: 0.9834
Epoch 10/10
469/469 [==============================] - 6s 13ms/step - loss: 0.0239 - accuracy: 0.9920 - val_loss: 0.0653 - val_accuracy: 0.9845
Test accuracy: 0.9845000500679016
Model saved to disk.
```
现在您已经成功地训练了一个MNIST模型,并将其保存为JSON格式和HDF5文件。
阅读全文