【发布时间】:2018-12-14 08:08:16
【问题描述】:
我正在尝试使用 PyTorch (v0.4.0) 开发一个简单的单层感知器来分类 AND 布尔运算。 我想通过使用 autograd 计算权重和偏差的梯度,然后以 SGD 方式更新它们来开发它。
代码很简单,如下:
# AND points and labels
data = torch.tensor([
[0, 0],
[0, 1],
[1, 0],
[1, 1]
], dtype=torch.float32)
labels = torch.tensor([0,0,0,1], dtype=torch.float32)
weights = torch.zeros(2, dtype=torch.float32, requires_grad=True)
bias = torch.zeros(1, requires_grad=True)
losses = []
epochs = 100
eta = 0.01
for epoch in range(epochs):
total_loss = 0
for idx in range(4):
# take current input
X = data[idx,:]
y = labels[idx]
# compute output and loss
out = torch.add(torch.dot(weights, X), bias)
loss = (out-y).pow(2)
total_loss += loss.item()
# backpropagation
loss.backward()
# compute accuracy and update parameters
with torch.no_grad():
weights -= eta * weights.grad
bias -= eta * bias.grad
# reset gradient to zero
weights.grad.zero_()
bias.grad.zero_()
losses.append(total_loss)
准确率达到 50%。
我尝试了不同的初始参数,也尝试了 PyTorch 的 SGD 优化器,但没有任何改变。 我知道 MSE 是一种回归损失,但我认为问题不存在。
有什么想法吗?
更新 平面是用这两行代码计算出来的
xr = np.linspace(0, 1, 10)
yr = (-1 / weights[1].item()) * (weights[0].item() * xr + bias.item())
plt.plot(xr,yr,'-')
【问题讨论】:
-
1.由此产生的飞机对我来说看起来是正确的。 2. 尝试将损失更改为 NLL。
-
平面不正确,因为在 AND 中它应该将右上角与所有其他点分开,因为它是唯一带有标签 1 的点。
-
你是如何计算平面的?
-
查看上面的更新问题
-
您是如何得出
yr的公式的?或者你从哪里得到的?
标签: pytorch perceptron