【发布时间】:2020-07-27 02:23:19
【问题描述】:
我是 Pytorch 的新手,所以我尝试通过创建简单的狗与猫分类来学习它。 代码:
class DogCatClassifier(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 32, 5)
self.conv2 = nn.Conv2d(32, 64, 5)
self.conv3 = nn.Conv2d(64, 128, 5)
self.fc1 = nn.Linear(512, 256)
self.fc2 = nn.Linear(256, 2)
def forward(self, x):
x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
print("1-st: ", x.shape)
x = F.max_pool2d(F.relu(self.conv2(x)), (2, 2))
print("2-nd: ", x.shape)
x = F.max_pool2d(F.relu(self.conv3(x)), (2, 2))
print("3-rd: ", x.shape)
x = torch.flatten(x, start_dim=1)
x = F.relu(self.fc1(x))
print("6-th: ", x.shape)
x = self.fc2(x) # bc this is our output layer. No activation here.
print("7-th: ", x.shape)
x = F.sigmoid(x)
print("8-th: ", x.shape)
return x
我传递的是单批数据(数据形状为(50, 1, 50, 50)
model = DogCatClassifier()
images, labels = next(iter(train_loader))
preds = model(images)
print(pred)
loss = F.binary_cross_entropy(preds, labels)
我的预测形状是 (50, 2),所以据我了解,F.binary_cross_entropy(preds, labels) 检查来自单个图像的两个预测,这就是为什么我针对 50 个标签得到 100 个预测。来自 tensorflow,我认为我可以实现相同的逻辑,例如使用 sigmoid 作为最后一次激活,使用 binary_cross_entropy 作为损失函数。我不明白的是如何使这段代码工作。
【问题讨论】:
标签: python pytorch loss-function