Pytorch基础篇--1

作者: 布口袋_天晴了 | 来源:发表于2019-07-18 17:41 被阅读0次

    源码:github code
    pytorch线性回归的例子

    import torch
    import torch.nn as nn
    import numpy as np
    import matplotlib.pyplot as plt
    
    # Hyper-parameters
    # 超参设置
    input_size = 1
    output_size = 1
    num_epochs = 60
    learning_rate = 0.001
    
    # Toy dataset
    # 数据
    x_train = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168],
                        [9.779], [6.182], [7.59], [2.167], [7.042],
                        [10.791], [5.313], [7.997], [3.1]], dtype=np.float32)
    
    y_train = np.array([[1.7], [2.76], [2.09], [3.19], [1.694], [1.573],
                        [3.366], [2.596], [2.53], [1.221], [2.827],
                        [3.465], [1.65], [2.904], [1.3]], dtype=np.float32)
    
    # Linear regression model
    # 线性回归模型
    model = nn.Linear(input_size, output_size)
    print(model.weight)
    print(model.bias)
    
    # Loss and optimizer
    # 损失函数和优化器
    criterion = nn.MSELoss()
    optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate)
    
    # Train the model
    # 模型训练
    for epoch in range(num_epochs):
        # Convert numpy arrays to torch tensors
        # numpy数据转换为tensor数据
        inputs = torch.from_numpy(x_train)
        targets = torch.from_numpy(y_train)
    
        # Forward pass
        outputs = model(inputs)
        loss = criterion(outputs, targets)
    
        # Backward and optimize
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()
    
        if (epoch + 1) % 5 == 0:
            print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch + 1, num_epochs, loss.item()))
    
    # Plot the graph
    # 画图--线性回归
    predicted = model(torch.from_numpy(x_train)).detach().numpy()
    plt.plot(x_train, y_train, 'ro', label='Original data')
    plt.plot(x_train, predicted, 'yo', label='Predict data')
    plt.plot(x_train, predicted, label='Fitted line')
    plt.legend()
    plt.show()
    
    # Save the model checkpoint
    # 保存模型
    torch.save(model.state_dict(), 'model.ckpt')
    

    Parameter containing:
    tensor([[-0.9154]], requires_grad=True)
    Parameter containing:
    tensor([0.8025], requires_grad=True)
    Epoch [5/60], Loss: 28.1747
    Epoch [10/60], Loss: 11.5182
    Epoch [15/60], Loss: 4.7704
    Epoch [20/60], Loss: 2.0368
    Epoch [25/60], Loss: 0.9293
    Epoch [30/60], Loss: 0.4806
    Epoch [35/60], Loss: 0.2989
    Epoch [40/60], Loss: 0.2252
    Epoch [45/60], Loss: 0.1954
    Epoch [50/60], Loss: 0.1833
    Epoch [55/60], Loss: 0.1784
    Epoch [60/60], Loss: 0.1764

    pytorch实现的简单线性回归

    相关文章

      网友评论

        本文标题:Pytorch基础篇--1

        本文链接:https://www.haomeiwen.com/subject/danllctx.html