复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13#导入所需要的包 import keras from keras.datasets import mnist from keras.layers import Dense from keras.models import Sequential from keras.optimizers import SGD #下载数据集 (x_train,y_train),(x_test,y_test) = mnist.load_data() #查看数据的size print(x_train.shape, y_train.shape) print(x_test.shape, y_test.shape)
此时输出的结果为:
复制代码
1
2
3
4#随机查看一下数据内容 import matplotlib.pyplot as plt im = plt.imshow(x_train[0],cmap="gray") plt.show()
输出为:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23#向量化图片,将28*28转化成1*784 x_train = x_train.reshape(60000,784) x_test = x_test.reshape(10000,784) #数据归一化 x_train = x_train/255 x_test = x_test/255 #将标签值y进行独热编码 keras.utils.to_categorical() y_train = keras.utils.to_categorical(y_train,10) y_test = keras.utils.to_categorical(y_test,10) #开始构建模型 model = Sequential() model.add(Dense(512, activation='relu', input_shape=(784,))) model.add(Dense(256, activation='relu')) model.add(Dense(10, activation='softmax')) #查看模型情况 model.summary()
输出的模型概况为:
复制代码
1
2
3
4
5#编译神经网络 model.compile(optimizer=SGD(), loss='categorical_crossentropy', metrics=['accuracy']) #训练网络 model.fit(x_train, y_train, batch_size=64, epochs=10, validation_data=(x_test, y_test))
执行结果:
复制代码
1
2
3
4#查看最终结果 score = model.evaluate(x_test, y_test) print("LOSS:",score[0]) print("ACCU:",score[1])
输出结果为:
完整版程序:
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60#导入所需要的包 import keras from keras.datasets import mnist from keras.layers import Dense from keras.models import Sequential from keras.optimizers import SGD #下载数据集 (x_train,y_train),(x_test,y_test) = mnist.load_data() #查看数据的size #此部分可省略 print(x_train.shape, y_train.shape) print(x_test.shape, y_test.shape) #随机查看一下图片 #此部分可省略 import matplotlib.pyplot as plt im = plt.imshow(x_train[0],cmap="gray") plt.show() #向量化图片,将28*28转化成1*784 x_train = x_train.reshape(60000,784) x_test = x_test.reshape(10000,784) #数据归一化 x_train = x_train/255 x_test = x_test/255 #将标签值y进行独热编码 keras.utils.to_categorical() y_train = keras.utils.to_categorical(y_train,10) y_test = keras.utils.to_categorical(y_test,10) #开始构建模型 model = Sequential() model.add(Dense(512, activation='relu', input_shape=(784,))) model.add(Dense(256, activation='relu')) model.add(Dense(10, activation='softmax')) #查看模型情况 #此部分可省略 model.summary() #编译神经网络 model.compile(optimizer=SGD(), loss='categorical_crossentropy', metrics=['accuracy']) #训练网络 model.fit(x_train, y_train, batch_size=64, epochs=10, validation_data=(x_test, y_test)) #查看结果 score = model.evaluate(x_test, y_test) print("LOSS:",score[0]) print("ACCU:",score[1])
来源:慕课网学习笔记
最后
以上就是缓慢冷风最近收集整理的关于深度学习入门--手写数字识别(Keras)的全部内容,更多相关深度学习入门--手写数字识别(Keras)内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复