《Python深度学习》第2章——深度学习数学基础code


from keras.datasets import mnist

# 加载 MNIST 数据集
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()

# 查看图片
import matplotlib.pyplot as plt 
plt.imshow(test_images[0], cmap=plt.cm.binary)
plt.show()

print(train_images.shape, len(train_labels))
print(test_images.shape, len(test_labels))

from keras import models
from keras import layers

# 构建网络
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'])

# 展开并除以255
train_images = train_images.reshape((60000, 28*28))
train_images = train_images.astype('float32') / 255.0

test_images = test_images.reshape((10000, 28*28))
test_images = test_images.astype('float32') / 255.0

# Converts a class vector (integers) to binary class matrix.
# 整数目标值改为分类目标值
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
print(test_labels[:10])
test_labels = to_categorical(test_labels)
print(test_labels[:10])
'''
[7 2 1 0 4 1 4 9 5 9]
# to_categorical 后
[[0. 0. 0. 0. 0. 0. 0. 1. 0. 0.]
 [0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [1. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 1. 0. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 0. 1. 0. 0. 0. 0.]
 [0. 0. 0. 0. 0. 0. 0. 0. 0. 1.]]
'''

# 训练(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, ' test loss: ', test_loss)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张欣-男

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值