Tensorflow: 提取训练模型的特征

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

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

  2. 如何获取训练/测试集中所有图像在分类之前的最终输出特征向量列表(在前向传递过程中)?

这是代码(完整版本可在 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 outpred = 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 modelcorrect_pred = tf.equal(tf.argmax(pred,1), tf.argmax(y,1))accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))# Launch the graphwith 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.})

回答:

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

return out

变为

return dense2, out

并且

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

变为

before_classification_layer, pred = alex_net(...)

然后你可以在调用sess.run()时获取before_classification_layer的值。请参阅tf.Session.runhttps://www.tensorflow.org/versions/0.6.0/api_docs/python/client.html#Session.run。请注意,fetches可以是一个列表,所以为了避免在你的示例代码中两次评估你的图,你可以这样做

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

而不是

# Calculate batch accuracyacc = sess.run(accuracy, feed_dict={...})# Calculate batch lossloss = sess.run(cost, feed_dict={...})

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

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注