![](https://img.haomeiwen.com/i20413470/b65b21e4d0d37e4a.png)
image.png
![](https://img.haomeiwen.com/i20413470/a86651c4e0d9aedc.png)
image.png
import torch
import torch.nn.functional as F
import os
import numpy as np
os.chdir(r"C:\Users\Eddie\Desktop")
def sigmoid(z):
"""The sigmoid function."""
return 1.0/(1.0+np.exp(-z))
# 1. prepare dataset
x_data = torch.tensor([[0,0,0,0,0,0,0,0,0,1.0],
[0,0,0,0,0,0,0,0,1.0,0],
[0,0,0,0,0,0,0,1.0,0,0],
[0,0,0,0,0,0,1.0,0,0,0],
[0,0,0,0,0,1.0,0,0,0,0],
[0,0,0,0,1.0,0,0,0,0,0],
[0,0,0,1.0,0,0,0,0,0,0],
[0,0,1.0,0,0,0,0,0,0,0],
[0,1.0,0,0,0,0,0,0,0,0],
[1.0,0,0,0,0,0,0,0,0,0]])
y_data = torch.tensor([[0,0,0,0],
[0,0,0,1.0],
[0,0,1.0,0],
[0,0,1.0,1.0],
[0,1.0,0,0],
[0,1.0,0,1.0],
[0,1.0,1.0,0],
[0,1.0,1.0,1.0],
[1.0,0,0,0],
[1.0,0,0,1.0]])
# 2. Design model
class LogisticRegressionModel(torch.nn.Module):
def __init__(self):
super(LogisticRegressionModel, self).__init__()
self.linear = torch.nn.Linear(10,4,bias = True)
def forward(self, x):
y_pred = torch.sigmoid(self.linear(x))
return y_pred
model = LogisticRegressionModel()
model.load_state_dict(torch.load(r"models\net.pth")) # load weights and bias data
# 3. Construct loss and optimizer
# criterion = torch.nn.BCELoss(weight=None, size_average=True, reduce=True)
criterion = torch.nn.MSELoss(reduction='mean')
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
#-------------------------------------------------------#
# 4. 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()
# 5. 保存权重数据
torch.save(obj=model.state_dict(), f=r"models\net.pth")
print("权重:",model.state_dict()['linear.weight'])
print("偏置:",model.state_dict()['linear.bias'])
# 6. 验证权重和偏置数据是否正确
w = np.array(model.state_dict()['linear.weight'])
b = np.array(model.state_dict()['linear.bias'])
w = np.transpose(w)
b = np.transpose(b)
y_hat = sigmoid(np.dot(x_data,w)+b)
print("结果:",y_hat)
print(np.int64(y_hat>0.5))
网友评论