目录
1、使用简单的逻辑斯蒂回归
import torch
import torch.nn.functional as F
准备数据:
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0.0], [0.0], [1.0]])
定义模型:
class LogisticRegressionModel(torch.nn.Module):
def __init__(self):
super(LogisticRegressionModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_pred = F.sigmoid(self.linear(x))
return y_pred
model = LogisticRegressionModel()
构建损失和优化器:
criterion = torch.nn.BCELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
训练:
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
输出w和b:
print('w = ', model.linear.weight.item())
print('b = ', model.linear.bias.item())
预测4.0时数据:
x_test = torch.Tensor([[4.0]])
y_test = model(x_test)
print('y_test = ', y_test.data)
2、代码绘图报错解决
参照原代码为:
import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0.0], [0.0], [1.0]])
# design module using class
class LogisticRegressionModel(torch.nn.Module):
def __init__(self):
super(LogisticRegressionModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_pred = F.sigmoid(self.linear(x))
return y_pred
model = LogisticRegressionModel()
# construct loss and optimizer
criterion = torch.nn.BCELoss(size_average=False)
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
# training cycle
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred, y_data)
print(epoch, loss.item())
optimizer.zero_grad()
loss.backward()
optimizer.step()
x = np.linspace(0.0, 10.0, 200)
print(x)
x_t = torch.Tensor(x).view((200, 1))
print(' ')
y_t = model(x_t)
y = y_t.data
print(y)
plt.plot(x, y)
plt.plot([0, 10], [0.5, 0.5], c='r')
plt.xlabel('Hours')
plt.ylabel('Probability of Pass')
plt.grid()
plt.show()
运行后报错:
解决方法:
将y = y_t.data.numpy 改为 y = y_t.data
得到结果图:
为什么呢?我百思不得其解,网上也找不到答案。但是今天太晚了,前面的知识以后再来探索吧!