[Python深度学习]第二章学习笔记

#加载keras中的MNIST数据集并准备图像数据
from keras.datasets import mnist
(train_images,train_labels),(test_images,test_labels) = mnist.load_data()
train_images = train_images.reshape((60000,28*28))#查看shape
train_image = train_images.astype('float32')/255#查看dtype,
#对输入数据预处理,unit8→float32,取值区间[0,255]→[0,1]
print(train_image.shape)
print(train_image.dtype)

#输出
(60000, 784)
float32
#搭建网络架构
from keras import models#加载keras里的包
from keras import layers
network = models.Sequential()
#该网络包含2个Dense层,它们是密集连接(也叫全连接)的神经层,
第二层是一个10路softmax层,返回一个由10个概率值(总和为1)组成的数组
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))

全连接层

第一个Dense层是512什么意思

#编译
network.compile(optimizer='rmsprop',#优化器
               loss='categorical_crossentropy',#损失函数
               metrics=['accuracy']#在训练和测试过程中监控的指标(metric))
#准备标签(?)
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
#训练网络
#在训练集上拟合(fit)模型
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)
#完整代码
from keras.datasets import mnist
from keras import models
from keras import layers
from keras.utils import to_categorical
(train_images,train_labels),(test_images,test_labels) = mnist.load_data()
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

network = models.Sequential()
network.add(layers.Dense(512,activation='relu',input_shape=(28*28,)))
network.add(layers.Dense(10,activation='softmax'))
            
network.compile(optimizer= 'rmsprop',
               loss = 'categorical_crossentropy',
               metrics = ['accuracy'])
            
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,python)