1. 程式人生 > >The expanded size of the tensor (256) must match the existing size (81) at non-singleton dimension1

The expanded size of the tensor (256) must match the existing size (81) at non-singleton dimension1

#RuntimeError: The expanded size of the tensor (256) must match the existing size (81) at non-singleton dimension 1

 在寫以下程式碼的時候遇到的

self.inputFC[4].bias.data=torch.eye(3).view(-1)

另一種原因:

import torch.nn as nn
net= nn.Sequential(
    nn.Linear(1024, 512),
    nn.ReLU(inplace=True),
    nn.Linear(512, 256),
    nn.ReLU(inplace=True),
    nn.Linear(256, 6),
)
cnn=nn.Sequential(
    nn.Conv2d(3,8,3,1,1),
    nn.Conv2d(8,19,3,1,1)
)
print(cnn[0].weight.data.size())
print(cnn[1].weight.data.size())

print(net[0].weight.data.size())

print(net[2].weight.data.size())

print(net[4].weight.data.size())

print(cnn[0].bias.data.size())
print(cnn[1].bias.data.size())

print(net[0].bias.data.size())

print(net[2].bias.data.size())

print(net[4].bias.data.size())

以上程式碼的輸出為:

  •  torch.Size([8, 3, 3, 3])
  • torch.Size([19, 8, 3, 3])
  • torch.Size([512, 1024])
  • torch.Size([256, 512])
  • torch.Size([6, 256])
  • torch.Size([8])
  • torch.Size([19])
  • torch.Size([512])
  • torch.Size([256])
  • torch.Size([6])

可以看到,weight.data的維度是定義時候的轉置。卷積層的權重的大小為【輸出通道,輸入通道,卷積核長,卷積核寬】。

所以初始化的時候要和這些大小相一致!

本來是要對bias用一個3階單位陣初始化,但是裡面的引數寫成了9,這樣就會用一個大於bias尺寸的資料來填充它。當然也可以用比bias尺寸小的資料來填充它,但是這樣做的話在進行feedforward的時候就會出現上面的錯誤。

不知道pytorch為什麼允許用尺寸不一樣的資料來初始化權重或者偏執,到了feed-forward才會報錯。應該在初始化的時候就不允許這樣的賦值操作,如果你知道原因,歡迎留言!