turn this into pytorch don't use alternative just pure translate : def…
- User
turn this into pytorch don't use alternative just pure translate : def weight_variable(shape, name=""): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial, name)
def bias_variable(shape, name=""): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name)
def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x, name=""): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
x = tf.placeholder(tf.float32, [None, 32*32])
First layer : 32 features
W_conv1 = weight_variable([5, 5, 1, 32], name='W1') b_conv1 = bias_variable([32], name='B1')
x_image = tf.reshape(x, [-1,32,32,1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1, name='Conv1') h_pool1 = max_pool_2x2(h_conv1, name='Pool1')
Second convolutional layer : 64 features
W_conv2 = weight_variable([5, 5, 32, 64], name='W2') b_conv2 = bias_variable([64], name='B2')
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2, name='Conv2') h_pool2 = max_pool_2x2(h_conv2, name='Pool2')
Densely connected layer : 1024 neurons, image size now 8x8
W_fc1 = weight_variable([8 * 8 * 64, 1024], name='W3') b_fc1 = bias_variable([1024], name='B3')
h_pool2_flat = tf.reshape(h_pool2, [-1, 8864], name='Pool3') h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1, 'MatMult3')
Dropout
keep_prob = tf.placeholder("float", name='KeepProb') h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob, name='Drop4')
Readout layer : softmax, 13 features
W_fc2 = weight_variable([1024, 13], name='W5') b_fc2 = bias_variable([13], name='B5')
y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2, name='Ypredict')
# Old single layer regression classifier
W = tf.Variable(tf.zeros([32*32, 13]))
b = tf.Variable(tf.zeros([13]))
y = tf.nn.softmax(tf.matmul(x, W) + b)
Ground truth labels if exist
y_ = tf.placeholder(tf.float32, [None, 13], name='Ytruth')
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv), name='CrossEntropy')
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy)
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1), name='CorrectPrediction') accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"), name='Accuracy')
Add ops to save and restore all the variables.
saver = tf.train.Saver()
Start Interactive session for rest of notebook (else we'd want to close session)
- Assistant