《python+深度学习》中的代码【1】

《python+深度学习》第二章事例中的代码如下

#$1 加载Keras 中的Mnist数据集
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
#看一下训练数据
print("This is train data:")
print("train_images.shape:",train_images.shape)
print("len(train_labels):",len(train_labels))
print("train_labels:",train_labels)
#看一下测试数据
print("this is test data:")
print("test_images.shape:",test_images.shape)
print("len(test_labels):",len(test_labels))
print("test_labels:",test_labels)
#本段代码用于忽略AVX2警告
import os 
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

#$2 网络架构
from keras import models
from keras import layers

#把网络分成密集连接(全连接)
network = models.Sequential()
network.add(layers.Dense(512, activation='relu',input_shape =(28*28,)))
#第二层是一个10路softmax层,他将返回一个由10个概率值组曾的数组。
network.add(layers.Dense(10,activation='softmax'))

#$3 编译步骤
#包含三个参数:损失函数loss function、优化器optimizer、监控指标metric
network.compile(optimizer='rmsprop',loss='categorical_crossentropy',metrics=['accuracy'])

#$4 准备图像数据
#取值范围缩放到[0,1]之间
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

#$5 对标签进行分类编码
from keras.utils import to_categorical

train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)

#开始训练此模型
network.fit(train_images, train_labels, epochs=5, batch_size=128)

#使用测试数据对模型进行测试
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)

你可能感兴趣的:(《python+深度学习》中的代码【1】)