python
import torch
import matplotlib.pyplot as plt
import numpy as np
python
import torchvision
# train_set = torchvision.datasets.MNIST(root='../dataset/mnist', train=True, download=True)
# test_set = torchvision.datasets.MNIST(root='../dataset/mnist', train=False, download=True)
您指定的路径 .../dataset/mnist 是一个相对路径,表示将 MNIST 数据集下载到当前目录的上级目录中的 dataset/mnist 目录中。
具体来说,在您的文件系统中,如果您的当前工作目录是 /home/user/,那么相对路径 .../dataset/mnist 将会是 /home/dataset/mnist。
python
class LinearModel(torch.nn.Module):
def __init__(self):
super(LinearModel, self).__init__()
self.linear = torch.nn.Linear(1, 1)
def forward(self, x):
y_pred = self.linear(x)
return y_pred
python
import torch.nn.functional as F
python
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
python
model = LogisticRegressionModel()
python
criterion = torch.nn.BCELoss(reduction = 'sum')
python
optimizer = torch.optim.SGD(model.parameters(),lr=0.01)
python
x_data = torch.Tensor([[1.0], [2.0], [3.0]])
y_data = torch.Tensor([[0], [0], [1]])
python
for epoch in range(1000):
y_pred = model(x_data)
loss = criterion(y_pred,y_data)
print(epoch,loss.item())
plt.scatter(epoch,loss.data)
optimizer.zero_grad()
loss.backward()
optimizer.step()
python
x = np.linspace(0, 10, 200) # 每周学习时间
x_t = torch.Tensor(x).view((200, 1)) # 200行1列的矩阵
y_t = model(x_t)
y = y_t.data.numpy()
plt.scatter(x, y)
plt.plot([0, 10], [0.5, 0.5], c='r')
plt.xlabel('Hours')
plt.ylabel('Probability of Pass')
plt.grid()
plt.show()