forked from MadryLab/mnist_challenge
-
Notifications
You must be signed in to change notification settings - Fork 2
/
model.py
76 lines (56 loc) · 2.37 KB
/
model.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
"""
The model is adapted from the tensorflow tutorial:
https://www.tensorflow.org/get_started/mnist/pros
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
class Model(object):
def __init__(self):
self.x_input = tf.placeholder(tf.float32, shape = [None, 784])
self.y_input = tf.placeholder(tf.int64, shape = [None])
self.x_image = tf.reshape(self.x_input, [-1, 28, 28, 1])
# first convolutional layer
W_conv1 = self._weight_variable([5,5,1,32])
b_conv1 = self._bias_variable([32])
h_conv1 = tf.nn.relu(self._conv2d(self.x_image, W_conv1) + b_conv1)
h_pool1 = self._max_pool_2x2(h_conv1)
# second convolutional layer
W_conv2 = self._weight_variable([5,5,32,64])
b_conv2 = self._bias_variable([64])
h_conv2 = tf.nn.relu(self._conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = self._max_pool_2x2(h_conv2)
# first fully connected layer
W_fc1 = self._weight_variable([7 * 7 * 64, 1024])
b_fc1 = self._bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# output layer
W_fc2 = self._weight_variable([1024,10])
b_fc2 = self._bias_variable([10])
self.pre_softmax = tf.matmul(h_fc1, W_fc2) + b_fc2
y_xent = tf.nn.sparse_softmax_cross_entropy_with_logits(
labels=self.y_input, logits=self.pre_softmax)
self.xent = tf.reduce_sum(y_xent)
self.y_pred = tf.argmax(self.pre_softmax, 1)
correct_prediction = tf.equal(self.y_pred, self.y_input)
self.num_correct = tf.reduce_sum(tf.cast(correct_prediction, tf.int64))
self.accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
@staticmethod
def _weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
@staticmethod
def _bias_variable(shape):
initial = tf.constant(0.1, shape = shape)
return tf.Variable(initial)
@staticmethod
def _conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')
@staticmethod
def _max_pool_2x2( x):
return tf.nn.max_pool(x,
ksize = [1,2,2,1],
strides=[1,2,2,1],
padding='SAME')