pytorch框架实现线性回归

pytorch框架实现线性回归

基础知识:call(),魔术方法的使用。

#__call___(): 使得类对象具有类似函数的功能。
class A():
    def __call__(self):
        print('i can be called like a function')
a = A()
a()  #结果:i can be called like a function

1、调用pytorch框架,创建张量w,求解动态计算图(dynamic computational graph)。

import torch

# 1、prepare dataset
# x,y是矩阵,3行1列 也就是说总共有3个数据,每个数据只有1个特征,其是mini-bach的形式,每个bach中有三个数据
x_data = torch.tensor([[1.0], [2.0], [3.0]])
y_data = torch.tensor([[2.0], [4.0], [6.0]])

2、通过class(类),设计线性模型。目的是为了前向传播forward,即计算y hat(预测值)

# 2、design model using class
"""
our model class should be inherit from nn.Module, which is base class for all neural network modules.
member methods __init__() and forward() have to be implemented
class nn.linear contain two member Tensors: weight and bias
class nn.Linear has implemented the magic method __call__(),which enable the instance of the class can
be called just like a function.Normally the forward() will be called 
"""

class LinearModel(torch.nn.Module):
    def __init__(self):
        super(LinearModel, self).__init__()
        # (1,1)是指输入x和输出y的特征维度,这里数据集中的x和y的特征都是1维的
        # 该线性层需要学习的参数是w和b  获取w/b的方式分别是~linear.weight/linear.bias
        self.linear = torch.nn.Linear(1, 1)   # (1,1)是指输入x和输出y的特征维度,这里数据集中的x和y的特征都是1维的

    def forward(self, x):
        y_pred = self.linear(x)     ##实现了__call___: 使得类对象具有类似函数的功能。
        return y_pred
        
model = LinearModel()  #创建线性模型,model

3、计算loss是为了进行反向传播,optimizer是为了更新梯度。
本实例是批量数据处理,不要被optimizer = torch.optim.SGD(model.parameters(), lr = 0.01)误导了,以为见了SGD就是随机梯度下降。要看传进来的数据是单个的还是批量的。这里的x_data是3个数据,是一个batch,调用的PyTorch API是 torch.optim.SGD,但这里的SGD不是随机梯度下降,而是批量梯度下降。也就是说,梯度下降算法使用的是随机梯度下降,还是批量梯度下降,还是mini-batch梯度下降,用的API都是 torch.optim.SGD。

# 3、construct loss and optimizer
# criterion = torch.nn.MSELoss(size_average = False)
criterion = torch.nn.MSELoss(reduction='sum')  #此时是把所有的损失相加,而不求平均
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)  # model.parameters()自动完成参数的初始化操作

4、进行100轮的循环训练,①前向传播,求y hat (输入的预测值)②根据y_hat和y_label(y_data)计算loss③反向传播 backward (计算梯度)④根据梯度,更新参数

# 4、training cycle forward, backward, update
for epoch in range(100):
    y_pred = model(x_data)  # forward:predict     1、算预测值
    loss = criterion(y_pred, y_data)  # forward: loss    2、算损失
    print(epoch, loss.item())

    optimizer.zero_grad()  # the grad computer by .backward() will be accumulated. so before backward, remember set the grad to zero,梯度清零
    loss.backward()  # backward: autograd,自动计算梯度    3、反馈,进行梯度运算
    optimizer.step()  # update 参数,即更新w和b的值    4、优化,更新参数(w,b)

print('w = ', model.linear.weight.item())
print('b = ', model.linear.bias.item())
#5、对训练的模型参数进行测试。
x_test = torch.tensor([[4.0]])
y_test = model(x_test)
print('y_pred = ', y_test.data)  #result:y_pred =  tensor([[7.6951]])
# print('y_pred = ', y_test.item()) #结果为:y_pred =  7.461838245391846

程序执行后的结果,显示了经过每轮的训练之后,模型的损失值是多少;经过100轮的训练之后,输出最后模型参数w和b的值;最终当输入张量为“4”时,模型的测试值。
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以为您提供使用PyTorch框架完成逻辑回归的代码示例。 首先,您需要导入PyTorch和其他必要的库: ```python import torch import torch.nn.functional as F import numpy as np ``` 然后,您可以定义一个LogisticRegression类来实现逻辑回归模型: ```python class LogisticRegression(torch.nn.Module): def __init__(self, input_dim): super(LogisticRegression, self).__init__() self.linear = torch.nn.Linear(input_dim, 1) def forward(self, x): x = self.linear(x) x = torch.sigmoid(x) return x ``` 在这个类中,我们定义了一个线性层,并使用sigmoid函数作为激活函数。这个类的输入维度可以根据您的需求进行更改。 接下来,您可以定义训练和测试函数: ```python def train(model, train_loader, criterion, optimizer, device): model.train() for data, target in train_loader: data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = criterion(output, target) loss.backward() optimizer.step() def test(model, test_loader, device): model.eval() correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) output = model(data) pred = torch.round(output) correct += pred.eq(target.view_as(pred)).sum().item() accuracy = 100. * correct / len(test_loader.dataset) print('Accuracy: {:.2f}%'.format(accuracy)) ``` 在train函数中,我们首先将数据和目标值移动到所选设备上,然后将梯度初始化为零。接下来,我们通过模型获取输出,计算损失,进行反向传播并更新参数。 在test函数中,我们首先将模型设置为评估模式,然后对测试集中的每个样本进行预测,并计算准确率。 最后,您可以使用以下代码来运行整个模型: ```python # 定义超参数 learning_rate = 0.01 batch_size = 64 num_epochs = 100 # 加载数据 train_data = np.load('train_data.npy') train_labels = np.load('train_labels.npy') test_data = np.load('test_data.npy') test_labels = np.load('test_labels.npy') train_dataset = torch.utils.data.TensorDataset(torch.from_numpy(train_data).float(), torch.from_numpy(train_labels).float()) train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True) test_dataset = torch.utils.data.TensorDataset(torch.from_numpy(test_data).float(), torch.from_numpy(test_labels).float()) test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False) # 初始化模型、损失函数和优化器 model = LogisticRegression(input_dim=train_data.shape[1]) criterion = torch.nn.BCELoss() optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate) # 将模型和数据移动到所选设备上 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) # 训练模型 for epoch in range(num_epochs): train(model, train_loader, criterion, optimizer, device) test(model, test_loader, device) ``` 在这个示例中,我们使用了numpy生成一些虚拟数据,并将其分成训练集和测试集。然后,我们定义了一些超参数,初始化了模型、损失函数和优化器,并将它们移动到所选设备上。最后,我们迭代了一些epoch,对模型进行训练和测试,并打印出准确率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值