import torch
import numpy as np
import matplotlib.pyplot as plt
x_data=torch.Tensor([[1.], [2.], [3.]])
y_data=torch.Tensor([[0.], [0.], [1.]])
class LogisticReg(torch.nn.Module):
def __init__(self):
super(LogisticReg,self).__init__()
self.linear=torch.nn.Linear(1,1)
def forward(self,x):
return torch.sigmoid(self.linear(x))
model = LogisticReg()
cirter=torch.nn.BCELoss()
optimizer=torch.optim.SGD(model.parameters(),lr=0.1)
E=500
for epoch in range(E):
y_pred=model(x_data)
loss=cirter(y_pred,y_data)
print("epoch{},loss={},w={},b={}".format(epoch,loss.item(),model.linear.weight.item(),model.linear.bias.data.item()))
optimizer.zero_grad()
loss.backward()
optimizer.step()
x_test=np.linspace(0,10,200)
x_t=torch.Tensor(x_test).view(200,1)
y_t=model(x_t)
y=y_t.data.numpy()
plt.plot(x_test,y)
plt.show()