b站up主:刘二大人《PyTorch深度学习实践》
教程: https://www.bilibili.com/video/BV1Y7411d7Ys?p=6&vd_source=715b347a0d6cb8aa3822e5a102f366fe
线性回归模型
:
t
o
r
c
h
.
n
n
.
L
i
n
e
a
r
激活函数:
t
o
r
c
h
.
s
i
g
m
o
i
d
交叉熵损失函数:
n
n
.
B
C
E
L
o
s
s
优化器:
o
p
t
i
m
.
A
d
a
m
数据集:
x
d
a
t
a
=
t
o
r
c
h
.
T
e
n
s
o
r
(
[
[
1.0
]
,
[
2.0
]
,
[
3.0
]
]
)
y
d
a
t
a
=
t
o
r
c
h
.
T
e
n
s
o
r
(
[
[
0
]
,
[
0
]
,
[
1
]
]
)
线性回归模型:torch.nn.Linear \\激活函数:torch.sigmoid \\交叉熵损失函数:nn.BCELoss \\优化器:optim.Adam \\数据集:x_{data} = torch.Tensor([[1.0],[2.0],[3.0]]) \\y_{data} = torch.Tensor([[0],[0],[1]])
线性回归模型:torch.nn.Linear激活函数:torch.sigmoid交叉熵损失函数:nn.BCELoss优化器:optim.Adam数据集:xdata=torch.Tensor([[1.0],[2.0],[3.0]])ydata=torch.Tensor([[0],[0],[1]])
import torch
import matplotlib.pyplot as plt
#数据集
x_data = torch.Tensor([[1.0],[2.0],[3.0]])
y_data = torch.Tensor([[0],[0],[1]])
epoch_p = []
loss_p = []
#设计模型
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
#加入sigmoid函数
y_pred = torch.sigmoid(self.linear(x))
return y_pred
model = Model()
#构造损失函数和优化器
criterion = torch.nn.BCELoss() #交叉熵损失函数,计算概率损失
optimizer = torch.optim.Adam(model.parameters(), lr = 0.01)
#train
for epoch in range(5000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
loss_p.append(loss.item())
epoch_p.append(epoch)
print("第{}个Epoch,loss = {:.6f}".format(epoch, loss))
optimizer.zero_grad()
loss.backward()
optimizer.step()
print("w = ",model.linear.weight.item())
print("b = ",model.linear.bias.item())
#测试
x_test = torch.Tensor([4.0])
y_test = model(x_test)
print("y_pred = ", y_test.data.item())
plt.figure()
plt.plot(epoch_p, loss_p, c = 'b')
plt.xlabel('Epoch')
plt.ylabel('loss')
plt.show()