如何在批量大小变化时计算类别得分

我的问题在最后,但首先我将解释我想实现的目标。

我有一个例子,我试图在自己的模型上实现。我正在创建一个对抗性图像,本质上我想绘制图像得分随epsilon值变化的情况。

假设我的model已经训练好了,在这个例子中我使用了以下模型…

x = tf.placeholder(tf.float32, shape=[None, 784])......# construct modellogits = tf.matmul(x, W) + bpred = tf.nn.softmax(logits)  # Softmax

接下来,假设我从mnist数据集中提取了一个数字2的图像数组,并将其保存到以下变量中…

# convert into a numpy array of shape [100, 784]labels_of_2 = np.concatenate(labels_of_2, axis=0)

所以现在,在我的例子中,下一步是尝试在每张图像上应用不同的epsilon值…

# random epsilon values from -1.0 to 1.0epsilon_res = 101eps = np.linspace(-1.0, 1.0, epsilon_res).reshape((epsilon_res, 1))labels = [str(i) for i in range(10)]num_colors = 10cmap = plt.get_cmap('hsv')colors = [cmap(i) for i in np.linspace(0, 1, num_colors)]# Create an empty array for our scoresscores = np.zeros((len(eps), 10))for j in range(len(labels_of_2)):   # Pick the image for this iteration   x00 = labels_of_2[j].reshape((1, 784))    # Calculate the sign of the derivative,    # at the image and at the desired class    # label    sign = np.sign(im_derivative[j])     # Calculate the new scores for each     # adversarial image      for i in range(len(eps)):        x_fool = x00 + eps[i] * sign        scores[i, :] = logits.eval({x: x_fool,                                 keep_prob: 1.0})

现在我们可以使用以下方式来绘制图像…

# Create a figureplt.figure(figsize=(10, 8))plt.title("Image {}".format(j))# Loop through the score functions for each# class label and plot them as a function of# epsilonfor k in range(len(scores.T)):    plt.plot(eps, scores[:, k],              color=colors[k],              marker='.',              label=labels[k])plt.legend(prop={'size':8})plt.xlabel('Epsilon')plt.ylabel('Class Score')plt.grid('on')

对于第一张图像,图表看起来会像下面这样…

enter image description here

现在是我的问题

假设我训练的模型使用了batch_size100,在这种情况下,以下这行代码将无法工作…

 scores[i, :] = logits.eval({x: x_fool,                                 keep_prob: 1.0})

为了使其工作,我需要向模型传递一个包含100张图像的数组,但在这个例子中,x_fool只是一张大小为(1, 784)的图像。

我想绘制不同epsilon值对类别得分的影响,但当我需要一次计算100张图像的得分时(因为我的模型是在批量大小为100的情况下训练的),我该如何操作呢?


回答:

您可以通过将其设置为None来选择不设定批量大小。这样,任何批量大小都可以使用。

然而,请注意这种不选择可能会带来适度的惩罚

如果您从头开始,这可以解决问题。如果您是从一个已训练的网络开始,该网络的批量大小为100,您可以创建一个与起始网络相似的测试网络,但批量大小除外。您可以将批量大小设置为1,或者再次设置为None

Related Posts

L1-L2正则化的不同系数

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

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

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

f1_score metric in lightgbm

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

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

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

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

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

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

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

发表回复

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