1、tensorflow版本查看
import tensorflow as tfprint ( 'Tensorflow Version:{}' . format ( tf. __version__) )
print ( tf. config. list_physical_devices( ) )
2、MNIST数据集下载与预处理
( train_images, train_labels) , ( test_images, test_labels) = tf. keras. datasets. mnist. load_data( )
train_images, test_images = tf. cast( train_images/ 255.0 , tf. float32) , tf. cast( test_images/ 255.0 , tf. float32)
tf.data.Dataset制作训练数据集
ds_train_image = tf. data. Dataset. from_tensor_slices( train_images)
ds_train_label = tf. data. Dataset. from_tensor_slices( train_labels)
ds_train = tf. data. Dataset. zip ( ( ds_train_image, ds_train_label) )
ds_train = ds_train. shuffle( 10000 ) . repeat( ) . batch( 64 ) print ( ds_train_image)
print ( ds_train_label)
print ( ds_train)
tf.data.Dataset制作测试数据集
ds_test = tf. data. Dataset. from_tensor_slices( ( test_images, test_labels) )
ds_test = ds_test. repeat( ) . batch( 64 ) print ( ds_test)
3、搭建MLP模型
from keras import Sequential
from keras. layers import Flatten, Dense
from keras import Inputmodel = Sequential( )
model. add( Input( shape= ( 28 , 28 ) ) )
model. add( Flatten( ) )
model. add( Dense( units= 256 , kernel_initializer= 'normal' , activation= 'relu' ) )
model. add( Dense( units= 10 , kernel_initializer= 'normal' , activation= 'softmax' ) )
4、模型训练
调用model.compile()函数对训练模型进行设置
model. compile ( optimizer= 'adam' , loss= 'sparse_categorical_crossentropy' , metrics= [ 'accuracy' ] )
调用model.fit()配置训练参数,开始训练,并保存训练结果。
steps_per_epochs = train_images. shape[ 0 ] // 64 H = model. fit( ds_train, steps_per_epoch= steps_per_epochs, validation_data= ds_test, validation_steps= 10000 // 64 , epochs= 10 , verbose= 1 )