1、准备数据
import tensorflow as tf
import numpy as np
from keras import datasets, layers, models
import matplotlib.pyplot as plt
#任务目标:实现手写数字识别
#数据集:MNIST手写数字数据集
#两种加载方法
# 加载本地MNIST数据集
data= np.load('/Users/code/MNIST_data/mnist.npz', allow_pickle=True)
x_train, y_train = data['x_train'], data['y_train']
x_test, y_test = data['x_test'], data['y_test']
# 下载MNIST手写数字数据集,使用TensorFlow内置的datasets.mnist.load_data()函数
data = datasets.mnist.load_data()
x_train, y_train = data['x_train'], data['y_train']
x_test, y_test = data['x_test'], data['y_test']
# 归一化像素值到0~1之间
x_train = x_train.astype('float32') / 255.
x_test = x_test.astype('float32') / 255.
#随机排序
perm = np.random.permutation(x_train.shape[0])
x_train = x_train[perm]
y_train = y_train[perm]
# 对label进行one-hot编码
y_train = tf.keras.utils.to_categorical(y_train, 10)
y_test = tf.keras.utils.to_categorical(y_test, 10)
2、构建模型