Python 3.x 在nn.crossentropyloss中将预期更改为多维而不是一维
我的目标是使用EMNIST数据集在Pytorch中进行多类图像分类。 作为损失函数,我想使用多类交叉熵损失 目前,我对损失函数的定义如下:Python 3.x 在nn.crossentropyloss中将预期更改为多维而不是一维,python-3.x,pytorch,cnn,Python 3.x,Pytorch,Cnn,我的目标是使用EMNIST数据集在Pytorch中进行多类图像分类。 作为损失函数,我想使用多类交叉熵损失 目前,我对损失函数的定义如下: criterion = nn.CrossEntropyLoss() iter = 0 for epoch in range(num_epochs): for i, (images, labels) in enumerate(train_loader): # Add a single channel dimensio
criterion = nn.CrossEntropyLoss()
iter = 0
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# Add a single channel dimension
# From: [batch_size, height, width]
# To: [batch_size, 1, height, width]
images = images.unsqueeze(1)
# Forward pass to get output/logits
outputs = model(images)
# Clear gradients w.r.t. parameters
optimizer.zero_grad()
# Forward pass to get output/logits
outputs = model(images)
# Calculate Loss: softmax --> cross entropy loss
loss = criterion(outputs, labels)
# Getting gradients w.r.t. parameters
loss.backward()
# Updating parameters
optimizer.step()
iter += 1
if iter % 500 == 0:
# Calculate Accuracy
correct = 0
total = 0
# Iterate through test dataset
for images, labels in test_loader:
images = images.unsqueeze(1)
# Forward pass only to get logits/output
outputs = model(images)
# Get predictions from the maximum value
_, predicted = torch.max(outputs.data, 1)
# Total number of labels
total += labels.size(0)
correct += (predicted == labels).sum()
accuracy = 100 * correct / total
# Print Loss
print('Iteration: {}. Loss: {}. Accuracy: {}'.format(iter, loss.data[0], accuracy))
我对我的模型进行如下培训:
criterion = nn.CrossEntropyLoss()
iter = 0
for epoch in range(num_epochs):
for i, (images, labels) in enumerate(train_loader):
# Add a single channel dimension
# From: [batch_size, height, width]
# To: [batch_size, 1, height, width]
images = images.unsqueeze(1)
# Forward pass to get output/logits
outputs = model(images)
# Clear gradients w.r.t. parameters
optimizer.zero_grad()
# Forward pass to get output/logits
outputs = model(images)
# Calculate Loss: softmax --> cross entropy loss
loss = criterion(outputs, labels)
# Getting gradients w.r.t. parameters
loss.backward()
# Updating parameters
optimizer.step()
iter += 1
if iter % 500 == 0:
# Calculate Accuracy
correct = 0
total = 0
# Iterate through test dataset
for images, labels in test_loader:
images = images.unsqueeze(1)
# Forward pass only to get logits/output
outputs = model(images)
# Get predictions from the maximum value
_, predicted = torch.max(outputs.data, 1)
# Total number of labels
total += labels.size(0)
correct += (predicted == labels).sum()
accuracy = 100 * correct / total
# Print Loss
print('Iteration: {}. Loss: {}. Accuracy: {}'.format(iter, loss.data[0], accuracy))
但是,我得到的错误是:
RuntimeError Traceback (most recent call last)
<ipython-input-15-c26c43bbc32e> in <module>()
21
22 # Calculate Loss: softmax --> cross entropy loss
---> 23 loss = criterion(outputs, labels)
24
25 # Getting gradients w.r.t. parameters
3 frames
/usr/local/lib/python3.6/dist-packages/torch/nn/functional.py in nll_loss(input, target, weight, size_average, ignore_index, reduce, reduction)
2113 .format(input.size(0), target.size(0)))
2114 if dim == 2:
-> 2115 ret = torch._C._nn.nll_loss(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
2116 elif dim == 4:
2117 ret = torch._C._nn.nll_loss2d(input, target, weight, _Reduction.get_enum(reduction), ignore_index)
RuntimeError: 1D target tensor expected, multi-target not supported
运行时错误回溯(最近一次调用)
在()
21
22#计算损失:softmax-->交叉熵损失
--->23损耗=标准(输出、标签)
24
25#获得梯度w.r.t.参数
3帧
/nll_损耗中的usr/local/lib/python3.6/dist-packages/torch/nn/functional.py(输入、目标、重量、尺寸平均值、忽略索引、减少、减少)
2113.格式(input.size(0)、target.size(0)))
2114如果尺寸=2:
->2115 ret=torch.\u C.\u nn.nll\u损失(输入、目标、重量、减少量、获取枚举(减少量)、忽略索引)
2116 elif dim==4:
2117 ret=torch.\u C.\u nn.nll\u loss2d(输入、目标、权重、减少、获取枚举(减少)、忽略索引)
运行时错误:需要1D目标张量,不支持多目标
我的CNN输出26个变量,我的目标变量也是26D
如何更改代码,使nn.crossentropyloss()需要26天的输入,而不是1天的输入?nn.crossentropyloss()(输入,目标)
需要input
是一个大小为batchsize X num_classes
的热向量,而target
是大小为batchsize
的真实类的id
因此,简而言之,您可以使用target=torch.argmax(target,dim=1)
更改您的目标,使其适合nn.CrossEntropy()
nn.CrossEntropy()(输入,目标)
期望input
成为大小为batchsize X num\u类的单热向量,并且target
是大小为batchsize
的真实类的id
因此,简而言之,您可以使用target=torch.argmax(target,dim=1)
更改您的目标,使其适合nn.CrossEntropy()
除了用户的答案之外,您还应该使用predicted=torch.argmax(output,dim=1)
获得预测的标签。现在你得到的是最大值,你所追求的是具有最大值的类
通过这种方式,您将获得0.0
精度,因此argmax
是正确的。除了用户的答案之外,您还应该使用predicted=torch.argmax(output,dim=1)
来获得预测的标签。现在你得到的是最大值,你所追求的是具有最大值的类
这样您将获得0.0
精度,因此argmax
是正确的