/
cifar_pai.py
153 lines (127 loc) · 5.01 KB
/
cifar_pai.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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import
import tensorflow as tf
from six.moves import urllib
import tarfile
import tflearn
from tflearn.data_utils import shuffle, to_categorical
from tflearn.layers.core import input_data, dropout, fully_connected
from tflearn.layers.conv import conv_2d, max_pool_2d
from tflearn.layers.estimator import regression
from tflearn.data_preprocessing import ImagePreprocessing
from tflearn.data_augmentation import ImageAugmentation
from tensorflow.python.lib.io import file_io
import os
import sys
import numpy as np
import pickle
import argparse
FLAGS = None
def load_data(dirname, one_hot=False):
X_train = []
Y_train = []
for i in range(1, 6):
fpath = os.path.join(dirname, 'data_batch_' + str(i))
data, labels = load_batch(fpath)
if i == 1:
X_train = data
Y_train = labels
else:
X_train = np.concatenate([X_train, data], axis=0)
Y_train = np.concatenate([Y_train, labels], axis=0)
fpath = os.path.join(dirname, 'test_batch')
X_test, Y_test = load_batch(fpath)
X_train = np.dstack((X_train[:, :1024], X_train[:, 1024:2048],
X_train[:, 2048:])) / 255.
X_train = np.reshape(X_train, [-1, 32, 32, 3])
X_test = np.dstack((X_test[:, :1024], X_test[:, 1024:2048],
X_test[:, 2048:])) / 255.
X_test = np.reshape(X_test, [-1, 32, 32, 3])
if one_hot:
Y_train = to_categorical(Y_train, 10)
Y_test = to_categorical(Y_test, 10)
return (X_train, Y_train), (X_test, Y_test)
#reporthook from stackoverflow #13881092
def reporthook(blocknum, blocksize, totalsize):
readsofar = blocknum * blocksize
if totalsize > 0:
percent = readsofar * 1e2 / totalsize
s = "\r%5.1f%% %*d / %d" % (
percent, len(str(totalsize)), readsofar, totalsize)
sys.stderr.write(s)
if readsofar >= totalsize: # near the end
sys.stderr.write("\n")
else: # total size is unknown
sys.stderr.write("read %d\n" % (readsofar,))
def load_batch(fpath):
object = file_io.read_file_to_string(fpath)
#origin_bytes = bytes(object, encoding='latin1')
# with open(fpath, 'rb') as f:
if sys.version_info > (3, 0):
# Python3
d = pickle.loads(object, encoding='latin1')
else:
# Python2
d = pickle.loads(object)
data = d["data"]
labels = d["labels"]
return data, labels
def main(_):
print(FLAGS.buckets)
print(FLAGS.checkpointDir)
print(FLAGS.test_para)
if tf.gfile.Exists(FLAGS.checkpointDir):
tf.gfile.DeleteRecursively(FLAGS.checkpointDir)
tf.gfile.MakeDirs(FLAGS.checkpointDir)
dirname = os.path.join(FLAGS.buckets, "")
(X, Y), (X_test, Y_test) = load_data(dirname)
print("load data done")
X, Y = shuffle(X, Y)
Y = to_categorical(Y, 10)
Y_test = to_categorical(Y_test, 10)
# Real-time data preprocessing
img_prep = ImagePreprocessing()
img_prep.add_featurewise_zero_center()
img_prep.add_featurewise_stdnorm()
# Real-time data augmentation
img_aug = ImageAugmentation()
img_aug.add_random_flip_leftright()
img_aug.add_random_rotation(max_angle=25.)
# Convolutional network building
network = input_data(shape=[None, 32, 32, 3],
data_preprocessing=img_prep,
data_augmentation=img_aug)
network = conv_2d(network, 32, 3, activation='relu')
network = max_pool_2d(network, 2)
network = conv_2d(network, 64, 3, activation='relu')
network = conv_2d(network, 64, 3, activation='relu')
network = max_pool_2d(network, 2)
network = fully_connected(network, 512, activation='relu')
network = dropout(network, 0.5)
network = fully_connected(network, 10, activation='softmax')
network = regression(network, optimizer='adam',
loss='categorical_crossentropy',
learning_rate=0.001)
# Train using classifier
model = tflearn.DNN(network, tensorboard_verbose=0)
model.fit(X, Y, n_epoch=50, shuffle=True, validation_set=(X_test, Y_test),
show_metric=True, batch_size=96, run_id='cifar10_cnn')
model_path = os.path.join(FLAGS.checkpointDir, "model.tfl")
print(model_path)
model.save(model_path)
# test_para = FLAGS.test
# print(test_para)
if __name__ == '__main__':
# parser = argparse.ArgumentParser()
# #获得buckets路径
# parser.add_argument('--buckets', type=str, default='',
# help='input data path')
# #获得checkpoint路径
# parser.add_argument('--checkpointDir', type=str, default='',
# help='output model path')
# FLAGS, _ = parser.parse_known_args()
FLAGS = tf.app.flags.FLAGS
tf.app.flags.DEFINE_string("buckets", "", "input data path")
tf.app.flags.DEFINE_string("checkpointDir", "", "output model path")
tf.app.flags.DEFINE_string("test_para", "", "test for help")
tf.app.run(main=main)