我正在嘗試構建一個簡單的 2 層網路,它有 2 個輸入和 1 個輸出,代碼如下:
num_input = 2
num_output = 1
# Input
x1 = torch.rand(1, 2)
# Weights
W1 = torch.rand(2,3)
W2 = torch.rand(3,1)
# biases
b1 = torch.rand(1,3)
b2 = torch.rand(1,1)
# Activation function
def f(inp):
inp[inp >= 0] = 1
inp[inp < 0] = 0
return inp
# Predict output
out = f(torch.mm(x1, W1) b1)
y=W2*out b2
print(y)
# Check solution
assert list(y.size()) == [1, num_output], f"Incorrect output size ({y.size()})"
print("nice!")
從這段代碼中我總是得到不正確的輸出大小,誰能給我一個提示,我怎樣才能得到正確的輸出大小?
uj5u.com熱心網友回復:
y=out@W2 b2
你在做元素乘法。這并沒有按照您的意愿改變輸出的大小。
為了清楚起見python 3.5,上面可以使用這個“@”語法——它做同樣的事情torch.mm()——即矩陣乘法。
尺寸:(現在)
現在您已將(1,2)輸入乘以(2,3)權重并添加(1,3)偏差。形狀是(1,3),然后你與矩陣相乘(1,3),(3,1)輸出是(1,1)并偏向于它,從而產生最終的輸出大小(1,1)。

尺寸(之前)

邊注:
您也可以使用nn.Linear輕松完成所有這些操作,而無需像這樣指定權重和偏差。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/470218.html
上一篇:梯度下降的線性回歸不會收斂
