使用全连接神经网络(写法不一样的demo)来实现手写数字的识别.
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.datasets import mnist
import matplotlib.pyplot as plt
from migrate.versioning.util import load_model
# 创建一个简单的全连接神经网络
model = Sequential()
model.add(Dense(50, activation='relu'))
model.add(Dense(10, activation='softmax'))
# 数据准备
(x_train, y_train), (x_test, y_test) = mnist.load_data()
y1 = []
for i in range(len(y_train)):
tmp = np.zeros([10])
tmp[y_train[i]] = 1
y1.append(tmp)
y2 = []
for i in range(len(y_test)):
tmp = np.zeros([10])
tmp[y_test[i]] = 1
y2.append(tmp)
# 重新定义为单个序列行的数据
x_train = np.reshape(x_train, [-1,784])
y_train = np.array(y1)
x_test = np.reshape(x_test, [-1, 784])
y_test = np.array(y2)
# 模型的编译
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# 模型的训练
history = model.fit(x_train, y_train, batch_size=800, epochs=80, verbose=1, validation_data=(x_test, y_test))
# 训练过程数据的可视化
# 绘制训练 & 验证的准确率值
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# 绘制训练 & 验证的损失值
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# 保存模型
model.save('model.h5')
# 加载模型,测试训练出来的模型
my_model = load_model('model.h5')
result = my_model.evaluate(x_test, y_test, batch_size=32)
print(result)
from keras import Input, Model
from keras.datasets import mnist
from keras.engine.saving import load_model
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy as np
# 模型定义
input = Input(shape=(784,), )
x = Dense(64, activation="relu")(input)
x = Dense(10, activation="softmax")(x)
model = Model(inputs=[input], outputs=[x])
model.compile(optimizer="adam", loss="categorical_crossentropy", metrics=['accuracy'])
# 数据准备
(x_train, y_train), (x_test, y_test) = mnist.load_data()
y1 = []
for i in range(len(y_train)):
tmp = np.zeros([10])
tmp[y_train[i]] = 1
y1.append(tmp)
y2 = []
for i in range(len(y_test)):
tmp = np.zeros([10])
tmp[y_test[i]] = 1
y2.append(tmp)
# 重新定义为单个序列行的数据
x_train = np.reshape(x_train, [-1,784])
y_train = np.array(y1)
x_test = np.reshape(x_test, [-1, 784])
y_test = np.array(y2)
# 拟合数据
history = model.fit(x_train, y_train, batch_size=800, epochs=100, verbose=1, validation_data=(x_test, y_test))
model.save("model3.h5")
# 训练过程数据的可视化
# 绘制训练 & 验证的准确率值
plt.plot(history.history['acc'])
plt.plot(history.history['val_acc'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()
# 绘制训练 & 验证的损失值
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper left')
plt.show()