pytorch自我学习基础(一) 线性回归

本文通过构建和训练一个包含多个隐藏层的神经网络,使用PyTorch框架进行深度学习实践。文章详细介绍了如何生成数据集,定义网络结构,设置损失函数与优化器,并通过迭代训练提高模型预测准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pytorch 版本 0.2.0

#coding=utf-8
from matplotlib import pylab as plt
import numpy as np
import random
import torch.nn as nn
import torch
from torch.autograd import Variable

num_inputs = 2
num_examples = 1000
true_w = [2, -3.4]
true_b = 4.2

features = np.random.randn(num_examples,num_inputs)
print features.shape

labels = features[:,0] * true_w[0] + features[:,1] * true_w[1] +true_b
labels += np.random.normal(scale=1.0,size=labels.shape)
print labels.shape

print features[0],labels[0]

# plt.scatter(features[:, 0], labels, 1)
# plt.show()
batch_size = 10
def data_iter(batch_size, features, labels):
    #num_examples = len(features)
    num_examples = features.shape[0]
    indices = list(range(num_examples))
    # 样本的读取顺序是随机的。
    random.shuffle(indices)
    for i in range(0, num_examples, batch_size):
        yield  features[indices[i: min(i + batch_size, num_examples)]],labels[indices[i: min(i + batch_size, num_examples)]]
'''
for X,y in data_iter(batch_size,features,labels):
    print X,y
'''
net = nn.Sequential(nn.Linear(2,10),
                    nn.Linear(10,10),
                    nn.Linear(10,1))
print net

loss_func= nn.MSELoss()
optimser = torch.optim.Adam(net.parameters(),lr=0.001)
for epoch in range(100):
    for X,y in data_iter(batch_size,features,labels):
        X = Variable(torch.from_numpy(X).float())
        y = Variable(torch.from_numpy(y).float())
        #print X,y
        output = net(X)
        loss = loss_func(output,y)
        optimser.zero_grad()
        loss.backward()
        optimser.step()

        print('epoch %d, loss: %f' % (epoch, loss.data.numpy()))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值