-
Notifications
You must be signed in to change notification settings - Fork 1
/
alexnet.py
184 lines (150 loc) · 8.2 KB
/
alexnet.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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import tensorflow as tf
import numpy as np
def alexnet_layer(tensor_in, n_filters, filter_shape, pool_size, activation=tf.nn.tanh,
padding='VALID', norm_depth_radius=4, dropout=None):
conv = learn.ops.conv2d(tensor_in,
n_filters=n_filters,
filter_shape=filter_shape,
activation=activation,
padding=padding)
pool = tf.nn.max_pool(conv, ksize=pool_size, strides=pool_size, padding=padding)
norm = tf.nn.lrn(pool, depth_radius=norm_depth_radius, alpha=0.001 / 9.0, beta=0.75)
if dropout:
norm = learn.ops.dropout(norm, dropout)
return norm
def alex_conv_pool_layer(tensor_in, n_filters, kernel_size, stride, pool_size, pool_stride,
activation_fn=tf.nn.tanh, padding='SAME'):
conv = tf.contrib.layers.convolution2d(tensor_in,
num_outputs=n_filters,
kernel_size=kernel_size,
stride=stride,
activation_fn=activation_fn,
padding=padding)
pool = tf.nn.max_pool(conv, ksize=pool_size, strides=pool_stride, padding=padding)
return pool
def alex_3_convs_pool_layer(tensor_in, activation_fn=tf.nn.tanh, padding='SAME'):
conv = tf.contrib.layers.convolution2d(tensor_in,
num_outputs=384,
kernel_size=[3, 3],
stride=1,
activation_fn=activation_fn,
padding=padding)
conv = tf.contrib.layers.convolution2d(conv,
num_outputs=384,
kernel_size=[3, 3],
stride=1,
activation_fn=activation_fn,
padding=padding)
conv = tf.contrib.layers.convolution2d(conv,
num_outputs=256,
kernel_size=[3, 3],
stride=1,
activation_fn=activation_fn,
padding=padding)
pool = tf.nn.max_pool(conv, ksize=(1, 3, 3, 1), strides=(1, 2, 2, 1), padding=padding)
return pool
def flatten_convolution(tensor_in):
tendor_in_shape = tensor_in.get_shape()
tensor_in_flat = tf.reshape(tensor_in, [tendor_in_shape[0].value or -1, np.prod(tendor_in_shape[1:]).value])
return tensor_in_flat
def dense_layer(tensor_in, layers, activation_fn=tf.nn.tanh, keep_prob=None):
if not keep_prob:
return tf.contrib.layers.stack(
tensor_in, tf.contrib.layers.fully_connected, layers, activation_fn=activation_fn)
tensor_out = tensor_in
for layer in layers:
tensor_out = tf.contrib.layers.fully_connected(tensor_out, layer,
activation_fn=activation_fn)
tensor_out = tf.contrib.layers.dropout(tensor_out, keep_prob=keep_prob)
return tensor_out
def alexnet_model(features, labels, mode, params):
#X, y, image_size=(-1, IMAGE_SIZE, IMAGE_SIZE, 3)):
net = tf.feature_column.input_layer(features, params['feature_columns'])
net = tf.reshape(net, (params['batch_size'], 48, 48, 1))
with tf.variable_scope('layer1'):
layer1 = alex_conv_pool_layer(net, 96, [11, 11], 4, (1, 3, 3, 1), (1, 2, 2, 1))
with tf.variable_scope('layer2'):
layer2 = alex_conv_pool_layer(layer1, 256, [5, 5], 2, (1, 3, 3, 1), (1, 2, 2, 1))
with tf.variable_scope('layer3'):
layer3 = alex_3_convs_pool_layer(layer2)
layer3_flat = flatten_convolution(layer3)
logits = dense_layer(layer3_flat, [4096, 4096, params['n_classes']], activation_fn=tf.nn.tanh, keep_prob=0.2)
# prediction is confidence
predicted_classes = tf.argmax(logits, 1)
if mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
'class_ids': predicted_classes[:, tf.newaxis],
'probabilities': tf.nn.softmax(logits),
'logits': logits,
}
return tf.estimator.EstimatorSpec(mode, predictions=predictions)
loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
accuracy = tf.metrics.accuracy(labels=labels,
predictions=predicted_classes,
name='acc_op')
metrics = {'accuracy': accuracy}
tf.summary.scalar('accuracy', accuracy[1])
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(
mode, loss=loss, eval_metric_ops=metrics)
assert mode == tf.estimator.ModeKeys.TRAIN
train_op = tf.contrib.layers.optimize_loss(
loss, tf.contrib.framework.get_global_step(), optimizer='Adagrad',
learning_rate=0.1)
return tf.estimator.EstimatorSpec(mode,loss=loss,train_op=train_op)
def my_alexnet(features, labels, mode, params):
training = False
if mode == tf.estimator.ModeKeys.TRAIN:
training = True
net = tf.feature_column.input_layer(features, params['feature_columns'])
if mode == tf.estimator.ModeKeys.PREDICT:
net = tf.reshape(net, (1,48,48,1))
else:
net = tf.reshape(net, (params['batch_size'], 48, 48, 1))
conv = tf.contrib.layers.convolution2d(net,
num_outputs=64,
kernel_size=[5,5],
stride=1,
activation_fn=tf.nn.relu,
padding='SAME')
norm = tf.nn.local_response_normalization(conv)
pool = tf.nn.max_pool(norm, ksize=(1,3,3,1), strides=(1,2,2,1), padding='SAME')
conv = tf.contrib.layers.convolution2d(pool,
num_outputs=64,
kernel_size=[5,5],
stride=1,
activation_fn=tf.nn.relu,
padding='SAME')
pool = tf.nn.max_pool(conv, ksize=(1,3,3,1), strides=(1,2,2,1), padding='SAME')
conv = tf.contrib.layers.convolution2d(pool,
num_outputs=128,
kernel_size=[4,4],
stride=1,
activation_fn=tf.nn.relu,
padding='SAME')
conv_flat = flatten_convolution(conv)
dropout = tf.contrib.layers.dropout(conv_flat, keep_prob=0.3, is_training=training)
net = tf.contrib.layers.fully_connected(dropout, 3072)
logits = tf.contrib.layers.fully_connected(net, params['n_classes'])
predicted_classes = tf.argmax(logits, 1)
if mode == tf.estimator.ModeKeys.PREDICT:
predictions = {
'class_ids': predicted_classes[:, tf.newaxis],
'probabilities': tf.nn.softmax(logits),
'logits': logits,
}
return tf.estimator.EstimatorSpec(mode, predictions=predictions)
loss = tf.losses.sparse_softmax_cross_entropy(labels=labels, logits=logits)
accuracy = tf.metrics.accuracy(labels=labels,
predictions=predicted_classes,
name='acc_op')
print('Accuracy',accuracy)
metrics = {'accuracy': accuracy}
tf.summary.scalar('accuracy', accuracy[1])
if mode == tf.estimator.ModeKeys.EVAL:
return tf.estimator.EstimatorSpec(
mode, loss=loss, eval_metric_ops=metrics)
assert mode == tf.estimator.ModeKeys.TRAIN
train_op = tf.contrib.layers.optimize_loss(
loss, tf.contrib.framework.get_global_step(), optimizer='Momentum', learning_rate=0.001)
return tf.estimator.EstimatorSpec(mode,loss=loss,train_op=train_op)