课程请见
《PyTorch深度学习实践》
# PyTorch
import torch
from torch import nn
from torch import optim
# For plotting
import matplotlib.pyplot as plt
# os
import os
os.environ["KMP_DUPLICATE_LIB_OK"] = "TRUE"
x_data = torch.Tensor([1., 2., 3.]).reshape(-1, 1)
y_data = torch.Tensor([0, 0, 1]).reshape(-1, 1)
class LogisticRegressionModel(nn.Module):
def __init__(self, input_dim=1, output_dim=1):
super(LogisticRegressionModel, self).__init__()
self.linear = nn.Linear(input_dim, output_dim)
def forward(self, x):
return torch.sigmoid(self.linear(x))
def init_weight(m):
if type(m) == nn.Linear:
nn.init.normal_(m.weight, std=0.01)
net = LogisticRegressionModel()
net.apply(init_weight)
criterion = nn.BCELoss()
optimizer = optim.SGD(net.parameters(), lr=0.01)
num_epochs = 1000
for epoch in range(num_epochs):
_y = net(x_data)
loss = criterion(_y, y_data)
optimizer.zero_grad()
loss.backward()
optimizer.step()
print(net.linear.weight.data)
test_data = torch.Tensor(list(range(11))).reshape(-1, 1)
y_pre = net(test_data)
plt.plot(test_data.tolist(), y_pre.tolist())
plt.xlabel('x')
plt.plot([0, 11], [0.5, 0.5], c='r')
plt.ylabel('pre y')
plt.grid()
plt.show()
和老师的
一模一样
版权声明:本文为weixin_45688580原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。