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

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

我有一个例子,我试图在自己的模型上实现。我正在创建一个对抗性图像,本质上我想绘制图像得分随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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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