一.实验环境
- jupyter lab
- tensorflow 2.2.0
- pythom3.6
二.步骤
1.导入包
import sklearn
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow import keras
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
2.导入数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
print(train_images.shape,train_labels.shape,test_images.shape,test_labels.shape)
3.处理数据集
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
from tensorflow.keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
print(train_images.shape,train_labels.shape,test_images.shape,test_labels.shape)
4.定义网络结构
model = keras.models.Sequential()
model.add(keras.layers.Dense(30,input_shape = train_images.shape[1:]))
for _ in range(15):
model.add(keras.layers.Dense(100,activation = 'relu'))
model.add(keras.layers.Dense(10,activation = 'softmax'))
model.compile(loss = "categorical_crossentropy",optimizer = "sgd",metrics = ["accuracy"])
history = model.fit(train_images, train_labels, epochs=100, batch_size=128)
5.检查在测试集上的表现
test_loss, test_acc = model.evaluate(test_images, test_labels)
最后准确率为97%
|