我有一個代碼(來自這里)來分類MINST數字。該代碼運行良好。這里他們使用了CrossEntropyLoss和Adam優化器。
模型代碼如下
class CNN(nn.Module)。
def __init__(self)。
super(CNN, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(
in_channels=1,
out_channels=16,  。
kernel_size=5,  。
stride=1,  。
padding=2,  。
nn.ReLU(),  。
nn.MaxPool2d(kernel_size=2),
)
self.conv2 = nn.Sequential(
nn. Conv2d(16, 32, 5, 1, 2),
nn.ReLU(),  。
nn.MaxPool2d(2),  。
)
#全連接層,輸出10類。
self.out = nn.Linear(32 * 7 * 7,10)
# self.softmax = torch.nn.Softmax(dim=1)
def forward(self, x)。
x = self.conv1(x)
x = self.conv2(x)
# flatten the output of conv2 to (batch_size, 32 * 7 * 7)/span>
x = x.view(x.size(0), -1)
output = self.out(x)
# output = self.softmax(output)/span>
return output, x # return x for visualization。
`b_x`的形狀 和 `b_y` 是的
torch. Size([100, 1, 28, 28]) torch.Size([100] ]
現在,我想從輸出層獲得連續值。比如說,我想讓輸出為alike,即1.0、0.9、8.6、7.0等。如果輸出層的值是1.0,并且標簽是1,這意味著預測是完美的。否則,就不完美。更簡單地說,我想把MNIST數字當成一個回歸問題。
因此,我將損失函式改為MSELoss,將優化器改為SGD(代碼的其余部分與網站相同)。但是現在,我得到了一個錯誤
/home/Opps_0/.local/lib/python3.8/site-packages/torch/nn/modules/loss.py:528。UserWarning。使用一個目標尺寸(torch.Size([100]),是不同于輸入尺寸(torch. Size([100, 10])。這很可能會因為廣播而導致不正確的結果。請確保它們具有相同的尺寸。
return F.mse_loss(input, target, reduction=self.reduction)
回溯(最近一次呼叫)。
File "/usr/lib/python3.8/runpy.py", line 194, in _run_module_as_main
return _run_code(code, main_globals, None,
File "/usr/lib/python3.8/runpy.py", line 87, in _run_code
exec(code, run_globals)
File "/home/Opps_0/Desktop/MNIST/src/train.py", line 60, in < module>
train(NB_EPOCS, model, loaders)
File "/home/Opps_0/Desktop/MNIST/src/train.py", line 45, in train
loss = criterion(output, b_y)
File "/home/Opps_0/.local/lib/python3.8/Site-packages/torch/nn/modules/module.py", line 889, in _call_impl
result = self.forward(*input, **kwargs)
檔案 "/home/Opps_0/.local/lib/python3.8/site-packages/torch/nn/modules/loss.py", line 528, in forward
return F.mse_loss(input, target, reduction=self.reduction)
檔案 "/home/Opps_0/.local/lib/python3.8/site-packages/torch/nn/functional.py", line 2925, in mse_loss
expanded_input, expanded_target = torch.broadcasting_tensors(input, target)
檔案 "/home/Opps_0/.local/lib/python3.8/Site-packages/torch/functional.py", 行 74, in broadcast_tensors
return _VF.broadcast_tensors(tensors) # type: ignore。
RuntimeError。張量a(10)的大小必須與張量b(100)在非單子維度的大小相匹配1。
你能告訴我,為了得到輸出層的連續值,我必須要改變什么嗎?
uj5u.com熱心網友回復:
假設你的目標是以(batch_size,)的形式出現的,那么大致是這樣的:
>>> model = CNN()
>>> criterion = nn.MSELoss()
>>> output, _ = model(torch.rand( 2, 1, 28, 28)
>>> b_y = torch.randint(0, 10, (2,)
張量([1, 2, 6, 5, 7] )
用MSELoss進行損失計算的結果是:
>>> loss = criterion(output, b_y)
RuntimeError: 張量
a(10)的大小必須與張量b(2)在非單一維度1的大小一致。
這意味著你的目標b_y的形狀是不正確的,它需要與output的形狀相匹配,即它需要是一個二維的張量。
由于你正在用回歸損失來優化這項任務,你可以將你的目標編碼為稀疏向量,也被稱為one-hot編碼。你可以使用內置的torch.nn.functional.one_hot輕松地做到這一點:
>>> ohe_target = torch.nn.functional.one_hot(b_y, num_classes=10)
張量([[0, 1, 0, 0, 0, 0, 0, 0, 0]。
[0, 0, 1, 0, 0, 0, 0, 0, 0]。
[0, 0, 0, 0, 0, 1, 0, 0, 0】。]
[0, 0, 0, 0, 1, 0, 0, 0, 0】。]
[0, 0, 0, 0, 0, 0, 1, 0, 0] ])
現在你可以正確計算損失了:
criterion(output, ohe_target)
tensor(0.1169, grad_fn=<MseLossBackward>)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/316563.html
標籤:
