我的问题在最后,但首先我将解释我想实现的目标。
我有一个例子,我试图在自己的模型上实现。我正在创建一个对抗性图像,本质上我想绘制图像得分随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')
对于第一张图像,图表看起来会像下面这样…
现在是我的问题
假设我训练的模型使用了batch_size
为100
,在这种情况下,以下这行代码将无法工作…
scores[i, :] = logits.eval({x: x_fool, keep_prob: 1.0})
为了使其工作,我需要向模型传递一个包含100张图像的数组,但在这个例子中,x_fool
只是一张大小为(1, 784)
的图像。
我想绘制不同epsilon值对类别得分的影响,但当我需要一次计算100张图像的得分时(因为我的模型是在批量大小为100的情况下训练的),我该如何操作呢?
回答:
您可以通过将其设置为None
来选择不设定批量大小。这样,任何批量大小都可以使用。
然而,请注意这种不选择可能会带来适度的惩罚。
如果您从头开始,这可以解决问题。如果您是从一个已训练的网络开始,该网络的批量大小为100,您可以创建一个与起始网络相似的测试网络,但批量大小除外。您可以将批量大小设置为1
,或者再次设置为None
。