TensorFlow2—20行代码实现CNN分类图片的例子

分享给有需要的同学。 下面的代码在Mnist数据集上的准确率在98.89%左右。如果有时间的同学可以通过增加网络层数或者卷积核的个数来提高精度。

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Flatten,Conv2D,MaxPool2D
from tensorflow.keras.datasets import mnist
#### read and preprocess data
(x_train,y_train),(x_test,y_test)=mnist.load_data()
x_train,x_test=x_train.reshape([-1,28,28,1])/255.0,x_test.reshape([-1,28,28,1])/255.0
#### contruct the model
model=Sequential()
model.add(Conv2D(filters=32,kernel_size=(3,3),activation='relu',input_shape=(28,28,1)))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Conv2D(filters=64,kernel_size=(3,3),activation='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
model.add(Flatten())     ##把卷积完之后的很多"小图片合并拉直"
model.add(Dense(10))
#### compile ; fit ; evaluate
model.compile(loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
			  optimizer="adam",
              metrics=['accuracy'])
model.fit(x=x_train,y=y_train,batch_size=100,epochs=20,verbose=2)
model.evaluate(x=x_test,y=y_test,verbose=2)

你可能感兴趣的:(TensorFlow,#,《Hands,On,ML》笔记)