深度学习一:手写数字识别(MNIST)

随着GPU硬件的飞速发展,把深度学习也带到了新的高度,所以这篇就讲一下深度学习的入门项目:手写数字识别。

引入Python库:

from tensorflow import keras
from tensorflow.keras import datasets,models,layers

导入数据集:

mnist=datasets.mnist
(train_x,train_y),(test_x,test_y)=mnist.load_data()

数据预处理:

train_x,test_x=train_x/255.,test_x/255.
train_y = keras.utils.to_categorical(train_y, num_classes=10)
test_y = keras.utils.to_categorical(test_y, num_classes=10)

创建模型:

model=models.Sequential()
model.add(layers.Flatten())
model.add(layers.Dense(128,activation='relu'))
model.add(layers.Dense(64,activation='relu'))
model.add(layers.Dense(10,activation='softmax'))

编译模型:

设置优化器,损失函数和精度

model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])

训练模型:

model.fit(train_x,train_y,validation_data=(test_x,test_y),batch_size=512,epochs=5)

模型概要与保存:

model.summary()
model.save('model.h5')

全部代码:

from tensorflow import keras
from tensorflow.keras import datasets,models,layers

mnist=datasets.mnist
(train_x,train_y),(test_x,test_y)=mnist.load_data()
train_x,test_x=train_x/255.,test_x/255.
train_y = keras.utils.to_categorical(train_y, num_classes=10)
test_y = keras.utils.to_categorical(test_y, num_classes=10)

model=models.Sequential()
model.add(layers.Flatten())
model.add(layers.Dense(128,activation='relu'))
model.add(layers.Dense(64,activation='relu'))
model.add(layers.Dense(10,activation='softmax'))

model.compile(optimizer='Adam',loss='categorical_crossentropy',metrics=['accuracy'])
model.fit(train_x,train_y,validation_data=(test_x,test_y),batch_size=512,epochs=5)

model.summary()
model.save('model.h5')

你可能感兴趣的:(深度学习,深度学习,python,pytorch)