Tensorflow:提取训练模型的特征

时间:2021-06-17 13:54:35

I have an implementation of the AlexNet. I'm interested in extracting the vector of features of a trained model before the fully-connected classification layers

我有一个AlexNet的实现。我有兴趣在完全连接的分类层之前提取训练模型的特征向量

  1. I want to first train the model (below I included the evaluation methods for training and testing).

    我想首先训练模型(下面我包括了培训和测试的评估方法)。

  2. How do I get a list of final output feature vectors (during the forward pass) for all the images in the training/test set before they get classified?

    如何在训练/测试集中的所有图像被分类之前获得最终输出特征向量列表(在前向传递期间)?

Here is the code (full version available https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3%20-%20Neural%20Networks/alexnet.py) :

这是代码(完整版可用https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3%20-%20Neural%20Networks/alexnet.py):

weights = {
    'wc1': tf.Variable(tf.random_normal([3, 3, 1, 64])),
    'wc2': tf.Variable(tf.random_normal([3, 3, 64, 128])),
    'wc3': tf.Variable(tf.random_normal([3, 3, 128, 256])),
    'wd1': tf.Variable(tf.random_normal([4*4*256, 1024])),
    'wd2': tf.Variable(tf.random_normal([1024, 1024])),
    'out': tf.Variable(tf.random_normal([1024, 10]))
}

biases = {
    'bc1': tf.Variable(tf.random_normal([64])),
    'bc2': tf.Variable(tf.random_normal([128])),
    'bc3': tf.Variable(tf.random_normal([256])),
    'bd1': tf.Variable(tf.random_normal([1024])),
    'bd2': tf.Variable(tf.random_normal([1024])),
    'out': tf.Variable(tf.random_normal([n_classes]))
}

def alex_net(_X, _weights, _biases, _dropout):
   # Reshape input picture


    _X = tf.reshape(_X, shape=[-1, 28, 28, 1])

    # Convolution Layer
    conv1 = conv2d('conv1', _X, _weights['wc1'], _biases['bc1'])
    # Max Pooling (down-sampling)
    pool1 = max_pool('pool1', conv1, k=2)
    # Apply Normalization
    norm1 = norm('norm1', pool1, lsize=4)
    # Apply Dropout
    norm1 = tf.nn.dropout(norm1, _dropout)

    # Convolution Layer
    conv2 = conv2d('conv2', norm1, _weights['wc2'], _biases['bc2'])
    ...
    # right before feeding the fully connected, classification layers
    # I'm interested in the vector after the weights 
    # are applied during the forward pass of a trained model.  
    dense1 = tf.reshape(norm3, [-1, _weights['wd1'].get_shape().as_list()[0]])
    # Relu activation
    dense1 = tf.nn.relu(tf.matmul(dense1, _weights['wd1']) + _biases['bd1'], name='fc1')

    # Relu activation
    dense2 = tf.nn.relu(tf.matmul(dense1, _weights['wd2']) + _biases['bd2'], name='fc2') 

    # Output, class prediction
    out = tf.matmul(dense2, _weights['out']) + _biases['out']
    return out


pred = alex_net(x, weights, biases, keep_prob)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred, y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)

# Evaluate model
correct_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    step = 1
    # Keep training until reach max iterations
    summary_writer = tf.train.SummaryWriter('/tmp/tensorflow_logs', graph_def=sess.graph_def)

    while step * batch_size < training_iters:
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        # Fit training using batch data
        sess.run(optimizer, feed_dict={x: batch_xs, y: batch_ys, keep_prob: dropout})
        if step % display_step == 0:
            # Calculate batch accuracy
            acc = sess.run(accuracy, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
            # Calculate batch loss
            loss = sess.run(cost, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.})
            print "Iter " + str(step*batch_size) + ", Minibatch Loss= " \
                  + "{:.6f}".format(loss) + ", Training Accuracy= " + "{:.5f}".format(acc)
        step += 1
    print "Optimization Finished!"
    # Calculate accuracy for 256 mnist test images
    print "Testing Accuracy:", sess.run(accuracy, feed_dict={x: mnist.test.images[:256], 
                                                             y: mnist.test.labels[:256], 
                                                             keep_prob: 1.})

1 个解决方案

#1


2  

It sounds like you want the value of dense2 from alex_net()? If so, you will need to return that from alex_net() in addition to out, so

听起来你想要alex_net()的dense2值?如果是这样,除了out之外,你还需要从alex_net()返回它,所以

return out

becomes

return dense2, out

and

pred = alex_net(x, weights, biases, keep_prob)

becomes

before_classification_layer, pred = alex_net(...)

Then you can fetch before_classification_layer when calling sess.run() whenever you want that value. See tf.Session.run in https://www.tensorflow.org/versions/0.6.0/api_docs/python/client.html#Session.run. Note that the fetches may be a list, so to avoid evaluating your graph twice in your example code, you can do

然后,只要您想要该值,就可以在调用sess.run()时获取before_classification_layer。请参阅https://www.tensorflow.org/versions/0.6.0/api_docs/python/client.html#Session.run中的tf.Session.run。请注意,提取可能是一个列表,因此为了避免在示例代码中对图表进行两次评估,您可以这样做

# Calculate batch accuracy and loss
acc, loss = sess.run([accuracy, cost], feed_dict={...})

instead of

# Calculate batch accuracy
acc = sess.run(accuracy, feed_dict={...})
# Calculate batch loss
loss = sess.run(cost, feed_dict={...})

(Adding before_classification_layer to that list when desired.)

(需要时将before_classification_layer添加到该列表中。)

#1


2  

It sounds like you want the value of dense2 from alex_net()? If so, you will need to return that from alex_net() in addition to out, so

听起来你想要alex_net()的dense2值?如果是这样,除了out之外,你还需要从alex_net()返回它,所以

return out

becomes

return dense2, out

and

pred = alex_net(x, weights, biases, keep_prob)

becomes

before_classification_layer, pred = alex_net(...)

Then you can fetch before_classification_layer when calling sess.run() whenever you want that value. See tf.Session.run in https://www.tensorflow.org/versions/0.6.0/api_docs/python/client.html#Session.run. Note that the fetches may be a list, so to avoid evaluating your graph twice in your example code, you can do

然后,只要您想要该值,就可以在调用sess.run()时获取before_classification_layer。请参阅https://www.tensorflow.org/versions/0.6.0/api_docs/python/client.html#Session.run中的tf.Session.run。请注意,提取可能是一个列表,因此为了避免在示例代码中对图表进行两次评估,您可以这样做

# Calculate batch accuracy and loss
acc, loss = sess.run([accuracy, cost], feed_dict={...})

instead of

# Calculate batch accuracy
acc = sess.run(accuracy, feed_dict={...})
# Calculate batch loss
loss = sess.run(cost, feed_dict={...})

(Adding before_classification_layer to that list when desired.)

(需要时将before_classification_layer添加到该列表中。)