深度学习-手写数字识别代码
Tensorflow2.0
训练模型
import tensorflow as tf from tensorflow import keras from tensorflow.keras.datasets import mnist from tensorflow.keras import layers (x_train,y_train),(x_test,y_test) = mnist.load_data() print(x_train.shape,y_train.shape) # 创建张量 x_train = tf.constant(x_train,dtype=tf.float32) x_test = tf.constant(x_test,dtype=tf.float32) # Reshape x_train4d = tf.reshape(x_train,[x_train.shape[0],28,28,1]) x_test4d = tf.reshape(x_test,[x_test.shape[0],28,28,1]) print(tf.shape(x_train4d),tf.shape(x_test4d)) #图像标准化 x_train4d,x_test4d = x_train4d/255.0,x_test4d/255.0 #模型搭建 model = keras.Sequential([ layers.Conv2D(filters=16,kernel_size=(5,5),padding='same',input_shape=(28,28,1),activation='relu'), layers.MaxPool2D(pool_size=(2,2)), layers.Conv2D(filters=36, kernel_size=(5, 5), padding='same', activation='relu'), layers.MaxPool2D(pool_size=(2,2)), layers.Dropout(0.25), layers.Flatten(), layers.Dense(128,activation='relu'), layers.Dropout(0.5), layers.Dense(10,activation='softmax') ]) print(model.summary()) #开始训练 model.compile(loss='sparse_categorical_crossentropy',optimizer='adam', metrics=['accuracy']) model.fit(x=x_train4d, y=y_train, validation_split=0.2,epochs=20, batch_size=300, verbose=2) model.save("./model.h5")
模型预测
import tensorflow as tf from tensorflow import keras from tensorflow.keras.datasets import mnist from tensorflow.keras import layers (x_train,y_train),(x_test,y_test) = mnist.load_data() print(x_train.shape,y_train.shape) # 创建张量 x_train = tf.constant(x_train,dtype=tf.float32) x_test = tf.constant(x_test,dtype=tf.float32) # Reshape x_train4d = tf.reshape(x_train,[x_train.shape[0],28,28,1]) x_test4d = tf.reshape(x_test,[x_test.shape[0],28,28,1]) print(tf.shape(x_train4d),tf.shape(x_test4d)) #图像标准化 x_train4d,x_test4d = x_train4d/255.0,x_test4d/255.0 new_model =tf.keras.models.load_model("./model.h5") print(new_model.summary()) new_model.evaluate(x_train4d,y_test)
预测结果