Convolutional Neural Networks翻译为卷积神经网络,常用在图像识别和语音分析等领域。CNN详细介绍参看:
- https://en.wikipedia.org/wiki/Convolutional_neural_network
- http://blog.youkuaiyun.com/zouxy09/article/details/8781543
- http://deeplearning.net/tutorial/lenet.html
使用TensorFlow创建CNN
执行结果:
下面使用tflearn重写上面代码,tflearn是TensorFlow的高级封装,类似Keras。
tflearn提供了更简单、直观的接口。和scikit-learn差不多,代码如下:
|
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
|
import
tflearn
from
tflearn
.
layers
.
conv
import
conv_2d
,
max_pool_2d
from
tflearn
.
layers
.
core
import
input_data
,
dropout
,
fully_connected
from
tflearn
.
layers
.
estimator
import
regression
train_x
,
train_y
,
test_x
,
test_y
=
tflearn
.
datasets
.
mnist
.
load_data
(
one_hot
=
True
)
train_x
=
train_x
.
reshape
(
-
1
,
28
,
28
,
1
)
test_x
=
test_x
.
reshape
(
-
1
,
28
,
28
,
1
)
# 定义神经网络模型
conv_net
=
input_data
(
shape
=
[
None
,
28
,
28
,
1
]
,
name
=
'input'
)
conv_net
=
conv_2d
(
conv_net
,
32
,
2
,
activation
=
'relu'
)
conv_net
=
max_pool_2d
(
conv
_net
,
2
)
conv_net
=
conv_2d
(
conv_net
,
64
,
2
,
activation
=
'relu'
)
conv_net
=
max_pool_2d
(
conv
_net
,
2
)
conv_net
=
fully_connected
(
conv_net
,
1024
,
activation
=
'relu'
)
conv_net
=
dropout
(
conv_net
,
0.8
)
conv_net
=
fully_connected
(
conv_net
,
10
,
activation
=
'softmax'
)
conv_net
=
regression
(
conv_net
,
optimizer
=
'adam'
,
loss
=
'categorical_crossentropy'
,
name
=
'output'
)
model
=
tflearn
.
DNN
(
conv_net
)
# 训练
model
.
fit
(
{
'input'
:
train_x
}
,
{
'output'
:
train_y
}
,
n_epoch
=
13
,
validation_set
=
(
{
'input'
:
test_x
}
,
{
'output'
:
test_y
}
)
,
snapshot_step
=
300
,
show_metric
=
True
,
run_id
=
'mnist'
)
model
.
save
(
'mnist.model'
)
# 保存模型
"""
model.load('mnist.model') # 加载模型
model.predict([test_x[1]]) # 预测
"""
|


1495

被折叠的 条评论
为什么被折叠?



