-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathcnn-minist.py
40 lines (30 loc) · 1.16 KB
/
cnn-minist.py
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
# -*- coding: utf-8 -*-
import os
import numpy as np
from sklearn.datasets import fetch_mldata
import npdl
def main(max_iter):
seed = 100
nb_data = 1000
print("loading data ....")
mnist = fetch_mldata('MNIST original', data_home=os.path.join(os.path.dirname(__file__), './data'))
X_train = mnist.data.reshape((-1, 1, 28, 28)) / 255.0
np.random.seed(seed)
X_train = np.random.permutation(X_train)[:nb_data]
y_train = mnist.target
np.random.seed(seed)
y_train = np.random.permutation(y_train)[:nb_data]
n_classes = np.unique(y_train).size
print("building model ...")
net = npdl.Model()
net.add(npdl.layers.Convolution(1, (3, 3), input_shape=(None, 1, 28, 28)))
net.add(npdl.layers.MeanPooling((2, 2)))
net.add(npdl.layers.Convolution(2, (4, 4)))
net.add(npdl.layers.MeanPooling((2, 2)))
net.add(npdl.layers.Flatten())
net.add(npdl.layers.Softmax(n_out=n_classes))
net.compile()
print("train model ... ")
net.fit(X_train, npdl.utils.data.one_hot(y_train), max_iter=max_iter, validation_split=0.1, batch_size=100)
if __name__ == '__main__':
main(10)