人工神经网络(2)
小批量梯度下降法
梯度下降法的优化
keras和tf.keras
Sequential模型
history属性:
Sequential模型实现手写数字识别
可运行:
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import tensorflow.keras
mnist = tf.keras.datasets.mnist
(train_x,train_y),(test_x,test_y)=mnist.load_data()
print(train_x.shape)
print(train_y.shape)
print(test_x.shape)
print(test_y.shape)
X_train,X_test=tf.cast(train_x/255.0,tf.float32),tf.cast(test_x/255.0,tf.float32)
y_train,y_test=tf.cast(train_y,tf.int16),tf.cast(test_y,tf.int16)
model = tf.keras.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28,28)))
model.add(tf.keras.layers.Dense(128,activation="relu"))
model.add(tf.keras.layers.Dense(10,activation="softmax"))
print(model.summary())
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['sparse_categorical_accuracy']
)
model.fit(X_train,y_train,batch_size=64,epochs=5,validation_split=0.2)
model.evaluate(X_test,y_test,verbose=2)
plt.axis("off")
plt.imshow(test_x[0],cmap="gray")
plt.show()
print(y_test[0])
print(np.argmax(model.predict(X_test[0:1]),axis=1))
for i in range(4):
plt.subplot(1,4,i+1)
plt.axis("off")
plt.imshow(test_x[i],cmap='gray')
plt.title(test_y[i])
plt.show()
y_pred=np.argmax(model.predict(X_test[0:4]),axis=1)
for i in range(4):
plt.subplot(1,4,i+1)
plt.axis("off")
plt.imshow(test_x[i],cmap='gray')
plt.title("y="+str(test_y[i])+"\ny_pred="+str(y_pred[i]))
plt.show()
for i in range(4):
num = np.random.randint(1,10000)
plt.subplot(1,4,i+1)
plt.axis("off")
plt.imshow(test_x[num],cmap='gray')
y_pred=np.argmax(model.predict(X_test[num:num+1]),axis=1)
title="y="+str(test_y[num])+"\ny_pred="+str(y_pred)
plt.title(title)
plt.show()
模型的保存和加载
model.save_weights("mnist_weights.h5")
model.save("mnist_model.h5")
model.load_weights("mnist_weights.h5")
print(model.evaluate(X_test,y_test,verbose=2))