【发布时间】:2020-11-15 02:43:15
【问题描述】:
我尝试使用 dropout 使用贝叶斯 CNN 实现图像分类。
我定义了两个类:
- 在训练阶段退出
- 考试不辍学(考试不辍学?请确认)
当我启动程序时,我重新制作了训练/测试准确度保持稳定,它们不会增加。我不明白问题出在哪里。
不知道是因为卷积和池化层参数的原因还是什么?请有任何想法。
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5, padding=2)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(6, 16, 5, padding=2)
self.fc1 = nn.Linear(16 * 8 * 8, 1024)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
def forward(self, x):
x = self.pool(F.relu(self.conv1(x)))
x = self.pool(F.relu(self.conv2(x)))
x = x.view(-1, 192 * 8 * 8)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(x))
x = self.fc3(x)
return x
# Lenet with MCDO
class Net_MCDO(nn.Module):
def __init__(self):
super(Net_MCDO, self).__init__()
self.conv1 = nn.Conv2d(3, 6, 5, padding=2)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(16, 192, 5, padding=2)
self.fc1 = nn.Linear(16 * 8 * 8, 120)
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
self.dropout = nn.Dropout(p=0.3)
def forward(self, x):
x = self.pool(self.dropout(self.conv1(x)))
x = self.pool(self.dropout(self.conv2(x)))
x = x.view(-1, 192 * 8 * 8)
x = F.relu(self.fc1(x))
x = F.relu(self.fc2(self.dropout(x)))
x = F.softmax(self.fc3(self.dropout(x)),dim=1)
return x
net=Net()
mcdo=Net_MCDO()
CE = nn.CrossEntropyLoss()
learning_rate=0.001
optimizer=optim.SGD(net.parameters(), lr=learning_rate, momentum=0.9)
epoch_num = 30
train_accuracies=np.zeros(epoch_num)
test_accuracies=np.zeros(epoch_num)
for epoch in range(epoch_num):
average_loss = 0.0
total=0
success=0
for i, data in enumerate(trainloader, 0):
inputs, labels = data
inputs, labels = Variable(inputs), Variable(labels)
optimizer.zero_grad()
outputs = mcdo(inputs)
loss=CE(outputs, labels)
loss.backward()
optimizer.step()
average_loss += loss.item()
_, predicted = torch.max(outputs.data, 1)
total += labels.size(0)
success += (predicted==labels.data).sum()
train_accuracy = 100.0*success/total
succes=0
total=0
for (inputs, labels) in testloader:
inputs, labels = Variable(inputs), Variable(labels)
outputs = net(inputs)
_,predicted = torch.max(outputs.data, 1)
total += labels.size(0)
success += (predicted==labels.data).sum()
test_accuracy = 100.0*success/total
print(u"epoch{}, average_loss{}, train_accuracy{},
test_accuracy{}".format(
epoch,
average_loss/n_batches,
train_accuracy,
100*success/total
))
#save
train_accuracies[epoch] = train_accuracy
test_accuracies[epoch] = 100.0*success/total
plt.plot(np.arange(1, epoch_num+1), train_accuracies)
plt.plot(np.arange(1, epoch_num+1), test_accuracies)
plt.show()
【问题讨论】:
-
完成了,我想现在更清楚了,谢谢
-
什么是
CE?你没有展示你是如何初始化它的。 -
我也不明白你为什么使用
mcdo处理训练数据和net处理测试数据?它们是独立初始化的,训练一个将如何改进另一个? -
我刚刚编辑过,
-
是的,我意识到这没有任何意义,我不知道如何使用一个模型测试模型而不会丢失,
标签: deep-learning pytorch classification bayesian conv-neural-network