批量大小更改时如何计算班级分数

时间:2017-04-30 21:05:24

标签: python-3.x matplotlib machine-learning tensorflow

我的问题在底部,但首先我将解释我想要实现的目标。

我有一个例子,我试图在我自己的模型上实现。我正在创建一个对抗图像,本质上我想要描绘当epsilon值改变时图像分数如何变化。

所以,让我们说我的link-to已经过培训,在这个例子中我使用的是以下模型......

model

接下来,我们假设我从x = tf.placeholder(tf.float32, shape=[None, 784]) ... ... # construct model logits = tf.matmul(x, W) + b pred = tf.nn.softmax(logits) # Softmax 数据集中提取了数字2的图像数组,并将其保存在以下变量中...

mnist

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

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

现在我们可以使用以下内容绘制图像...

# random epsilon values from -1.0 to 1.0
epsilon_res = 101
eps = np.linspace(-1.0, 1.0, epsilon_res).reshape((epsilon_res, 1))
labels = [str(i) for i in range(10)]

num_colors = 10
cmap = plt.get_cmap('hsv')
colors = [cmap(i) for i in np.linspace(0, 1, num_colors)]


# Create an empty array for our scores
scores = 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})

对于第一张图片,图表看起来如下......

enter image description here

现在这是我的问题

让我们说我训练过的模型使用了# Create a figure plt.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 # epsilon for 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

为了实现这一点,我需要将100个图像的数组传递给模型,但在这种情况下, scores[i, :] = logits.eval({x: x_fool, keep_prob: 1.0}) 只是一个大小为x_fool的图像。

我想绘制不同epsilon值对任何一个图像的类别分数的影响,但是当我需要一次计算(1, 784)个图像的分数时,我怎么能这样做(因为我的模型已经过训练batch_size为100)?

2 个答案:

答案 0 :(得分:1)

您可以选择不选择批量大小,方法是将其设置为None。这样,可以使用任何批量大小。

但是,请记住,这种非选择可以与a moderate penalty结合使用。

如果您从头开始重新启动,则会修复此错误。如果从批量大小为100的现有受过训练的网络开始,则可以创建与批处理大小类似的起始网络的测试网络。您可以将批量大小设置为1,或者再次设置为None

答案 1 :(得分:0)

我意识到问题不在于batch_size,而在于我尝试传递给模型的图像格式。正如 user1735003 指出的那样,batch_size并不重要。

我无法将图像传递给模型的原因是因为我正在传递它...

x_fool = x00 + eps[i] * sign
scores[i, :] = logits.eval({x: x_fool})

问题在于图像的形状只是(784,),而占位符需要接受形状shape=[None, 784]的图像数组,所以需要做的是{{1图像。

reshape

现在我的图像是形状x_fool = labels_of_2[0].reshape((1, 784)) + eps[i] * sign scores[i, :] = logits.eval({x:x_fool}) ,现在可以由占位符接受。