【问题标题】:How to predict a single image with Skorch?如何使用 Skorch 预测单个图像?
【发布时间】:2019-12-10 18:12:49
【问题描述】:

我刚刚使用 Skorch 创建了一个神经网络来检测图片上的飞机,并使用形状为 (40000, 64, 64, 3) 的火车数据集对其进行了训练。

然后我用(15000, 64, 64, 3)的测试数据集对其进行了测试。

module = nn.Sequential(
    nn.Conv2d(3, 64, 3),
    nn.BatchNorm2d(64),
    nn.ReLU(),
    nn.MaxPool2d(2),
    nn.Conv2d(64, 64, 3),
    nn.BatchNorm2d(64),
    nn.ReLU(),
    nn.MaxPool2d(2),
    nn.Conv2d(64, 64, 3),
    nn.BatchNorm2d(64),
    nn.ReLU(),
    nn.MaxPool2d(2),
    nn.Flatten(),
    nn.Linear(6 * 6 * 64, 256),
    nn.Linear(256, 256),
    nn.ReLU(),
    nn.Linear(256, 2),
    nn.Softmax(),
)

early_stopping = EarlyStopping(monitor='valid_loss', lower_is_better=True)
net = NeuralNetClassifier(
    module,
    max_epochs=20,
    lr=1e-4,
    callbacks=[early_stopping],
    # Shuffle training data on each epoch
    iterator_train__shuffle=True,
    device="cuda" if torch.cuda.is_available() else "cpu",
    optimizer=optim.Adam
)
net.fit(
    train_images_balanced.transpose((0, 3, 1, 2)).astype(np.float32),
    train_labels_balanced
)

现在我需要在 512*512 的图片上进行测试,所以我有了一个新的数据集(30, 512, 512, 3)
所以我做了一个滑动窗口代码,它允许我将图片分成 64*64 部分。

def sliding_window(image, stepSize, windowSize):
# slide a window across the image
for y in range(0, image.shape[0], stepSize):
    for x in range(0, image.shape[1], stepSize):
        # yield the current window
        yield (x, y, image[y:y + windowSize[1], x:x + windowSize[0]])

现在我希望能够预测每张 64*64 图像是否包含飞机,但我不知道该怎么做,因为 net.predict() 将数据集作为参数(arg : dim 4)

【问题讨论】:

  • 只需使用img.unsqueeze(0)为图像添加额外的暗淡?

标签: python neural-network deep-learning pytorch skorch


【解决方案1】:

net.predict() 将数据集作为参数 (arg : dim 4)

net.predict 接受多种数据格式,其中包括数据集。但是,对于您的情况,最好是接受火炬张量或 numpy 数组 - 确实如此!只需将您的 64x64 块传递给 net.predict,如下所示:

# (n, 512, 512, 3)
X = my_data
# (n, 4096, 64, 64, 3)
X = sliding_window(X, 64, 64)
# (n * 4096, 64, 64, 3)
X = X.reshape(-1, 64, 64, 3)
y = net.predict(X)

【讨论】:

  • 谢谢!这是我实际使用的: image = np.expand_dims(image, axis=0)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-08
  • 2021-08-01
  • 2017-08-18
  • 2020-11-29
  • 2021-01-28
  • 2020-05-14
  • 2020-04-05
相关资源
最近更新 更多