Reputation: 1163
I want to extract CNN activations from the fully connected layer in a convolution neural network using tensorflow. In the following post, a user asked that question:
How to extract activation from CNN layers using tensorflow?
And the answer is this :
sess = tf.InteractiveSesssion()
full_connected = ....
value_of_fully_connected = sess.run(fully_connected,feed_dict={your_placeholders_and_values)
However, in my code, the fully connected layer is separated from the tf.session()
. and I have this code for the function that computes the convolutions:
def conv_net(x, weights, biases):
conv1 = conv2d(x, weights['wc1'], biases['bc1'])
conv1 = maxpool2d(conv1, k=2)
conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
conv2 = maxpool2d(conv2, k=2)
conv3 = conv2d(conv2, weights['wc3'], biases['bc3'])
conv3 = maxpool2d(conv3, k=2)
# Fully connected layer
fc1 = tf.reshape(conv3, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
return out
And then the prediction :
pred = conv_net(x, weights, biases)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
And here is the training:
with tf.Session() as sess:
sess.run(init)
train_loss = []
test_loss = []
train_accuracy = []
test_accuracy = []
summary_writer = tf.summary.FileWriter('./Output', sess.graph)
for i in range(training_iters):
for batch in range(len(train_X)//batch_size):
batch_x = train_X[batch*batch_size:min((batch+1)*batch_size,len(train_X))]
batch_y = train_y[batch*batch_size:min((batch+1)*batch_size,len(train_y))]
# Run optimization op (backprop).
# Calculate batch loss and accuracy
opt = sess.run(optimizer, feed_dict={x: batch_x,
y: batch_y})
loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
y: batch_y})
print("Iter " + str(i) + ", Loss= " + \
"{:.6f}".format(loss) + ", Training Accuracy= " + \
"{:.5f}".format(acc))
print("Optimization Finished!")
# Calculate accuracy for all 10000 mnist test images
test_acc,valid_loss = sess.run([accuracy,cost], feed_dict={x: test_X,y : test_y})
train_loss.append(loss)
test_loss.append(valid_loss)
train_accuracy.append(acc)
test_accuracy.append(test_acc)
print("Testing Accuracy:","{:.5f}".format(test_acc))
summary_writer.close()
As you can see, the fully connected layer is inside the function conv_net()
, and I cannot seem to have access to that from inside tf.session()
code.
I need to have access to that fully connected layer so I can use the answer in the post above. How can I do that?
Upvotes: 0
Views: 1142
Reputation: 832
in python, you can return a list of output from a function. So, I would do something like:
def conv_net(x, weights, biases):
conv1 = conv2d(x, weights['wc1'], biases['bc1'])
conv1 = maxpool2d(conv1, k=2)
conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
conv2 = maxpool2d(conv2, k=2)
conv3 = conv2d(conv2, weights['wc3'], biases['bc3'])
conv3 = maxpool2d(conv3, k=2)
# Fully connected layer
fc1 = tf.reshape(conv3, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
return [out,fc1]
and when you want to get the outputs, you do:
pred, fcn = conv_net(x, weights, biases)
When you wanna see the result inside the session, do:
fcn_evaluated = sess.run(fcn)
print(fcn_evaluated)
Upvotes: 1