线性回归对房屋价格预测,从零开始实现

线性回归对房屋价格预测

这是我第一次写博客,可能会有很多排版的问题,也可能有不懂的地方,写的不好的地方希望大家能够批评指正。

首先,考虑一下需要用到哪写库的载入,torch库必不可少,matplotlib绘图库 也是必不可少、numpy库是用来数据处理的也得要,然后random模块也是需要的。目前就是这些了,后面需要再用到的话,就再往里面加,写代码是一个循序渐进的过程,不可能一下子把所有的库都想到,最基本的一些可以先想到就好了。

import torch
from matplotlib import pyplot as plt
import numpy as np
import random
from torch import nn

接下来,我们就要生成随机的数据,使用线性模型来生成数据集,生成一个1000个样本的数据集,为了验证我们最后数据拟合的效果,我们在生成数据集的时候,就直接给定参数来生成数据集: price=w1⋅area+w2⋅age+b
其中w1=2,w2=-3.4,b=4.2

代码如下:

设定输入的特征值的个数,由于我们在设定的时候只取了w1和w2,所以这里的inputs=2

num_inputs = 2

我们随机生成1000个样本点

num_examples = 1000

set true weight and bias in order to generate corresponded label

true_w = [2, -3.4]
true_b = 4.2

features = torch.randn(num_examples, num_inputs,
dtype=torch.float32)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float32)

plt.scatter(features[:, 1].numpy(), labels.numpy(), 1)
plt.show()

显示出图像如下:
在这里插入图片描述

读取数据集

定义一个函数来载入数据集,定义这个数据集
def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
random.shuffle(indices) # random read 10 samples
for i in range(0, num_examples, batch_size):
j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # the last time may be not enough for a whole batch
yield features.index_select(0, j), labels.index_select(0, j)

batch_size = 10

for X, y in data_iter(batch_size, features, labels):
print(X, ‘\n’, y)
break

我们对这个定义的这个函数取前十个测试一下,然后打印出来。X是一个10乘2的tensor 而y是一个1乘10的label。

初始化我们的模型参数

在这个模块,我们需要对设定的参数进行初始化话,首先对w【w1,w2】进行均值为0,方差为1的初始化,并且对1进行0矩阵操作。最后我们告诉这三个参数,你们都是需要梯度信息,所以设定requires_grad=True。
代码如下:
w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32)
b = torch.zeros(1, dtype=torch.float32)

w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)

定义回归的模型

定义用来训练参数的训练模型:price=warea⋅area+wage⋅age+b

def linreg(X, w, b):
return torch.mm(X, w) + b

定义损失函数

在损失函数这个快,对于一般的回归模型,我还是建议用mse,也就是均方差误差损失函数

我们使用的是均方误差损失函数:
loss = 1/2(y1-y)*(y1-y)

其中y1代表我们的预测值,而y代表真实值,也就是标签值。
代码如下:
def squared_loss(y_hat, y):
return (y_hat - y.view(y_hat.size())) ** 2 / 2

定义优化函数

在优化函数这块,最普通,最常用的,在大样本情况下,效果比较好的就是随机梯度下降法(SGD)

(w,b)←(w,b)−η|B|∑i∈B∂(w,b)l(i)(w,b)

代码如下:
def sgd(params, lr, batch_size):
for param in params:
param.data -= lr * param.grad / batch_size

训练

当数据集也有了,模型、损失函数和优化函数都设计好了,接下来就是选取一个学习率Lr和epoch进行模型的训练咯。
代码如下:
lr = 0.03
num_epochs = 5

net = linreg#实例化网络
loss = squared_loss

for epoch in range(num_epochs): # training repeats num_epochs times
# in each epoch, all the samples in dataset will be used once

# X is the feature and y is the label of a batch sample
for X, y in data_iter(batch_size, features, labels):
    l = loss(net(X, w, b), y).sum()  
    # calculate the gradient of batch sample loss 
    l.backward()  
    # using small batch random gradient descent to iter model parameters
    sgd([w, b], lr, batch_size)  
    # reset parameter gradient
    w.grad.data.zero_()
    b.grad.data.zero_()
train_l = loss(net(features, w, b), labels)
print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))

这段代码需要注意的是,在每一次迭代完成之后,我们必须要对现有的参数进行梯度清零,如果不清零就可能会出现收敛不了等情况。

print(w, true_w, b, true_b)

最后打印出我们的真实值和预测出来的值来进行比较。

总结

回归问题的思路比较清晰,只需要按部就班,无论是几个特征值,我们都可以自己对放假进行预测。另外,打开我们的链家网,或者是任何一个租房APP或者网页,再去学习一下爬虫技术,自己估算一下,自己家的房子价值是多少吧!! 行动起来。

整体的代码如下:

import torch
from IPython import display
from matplotlib import pyplot as plt
import numpy as np
import random

num_inputs = 2

num_examples = 1000

true_w = [2, -3.4]
true_b = 4.2

features = torch.randn(num_examples, num_inputs,
dtype=torch.float32)
labels = true_w[0] * features[:, 0] + true_w[1] * features[:, 1] + true_b
labels += torch.tensor(np.random.normal(0, 0.01, size=labels.size()), dtype=torch.float32)

plt.scatter(features[:, 1].numpy(), labels.numpy(), 1)

def data_iter(batch_size, features, labels):
num_examples = len(features)
indices = list(range(num_examples))
random.shuffle(indices) # random read 10 samples
for i in range(0, num_examples, batch_size):
j = torch.LongTensor(indices[i: min(i + batch_size, num_examples)]) # the last time may be not enough for a whole batch
yield features.index_select(0, j), labels.index_select(0, j)

batch_size = 10

for X, y in data_iter(batch_size, features, labels):
print(X, ‘\n’, y)
break

w = torch.tensor(np.random.normal(0, 0.01, (num_inputs, 1)), dtype=torch.float32)
b = torch.zeros(1, dtype=torch.float32)

w.requires_grad_(requires_grad=True)
b.requires_grad_(requires_grad=True)
def linreg(X, w, b):
return torch.mm(X, w) + b

def squared_loss(y_hat, y):
return (y_hat - y.view(y_hat.size())) ** 2 / 2

def sgd(params, lr, batch_size):
for param in params:
param.data -= lr * param.grad / batch_size # ues .data to operate param without gradient track

lr = 0.03
num_epochs = 5

net = linreg
loss = squared_loss

for epoch in range(num_epochs): # training repeats num_epochs times
# in each epoch, all the samples in dataset will be used once

# X is the feature and y is the label of a batch sample
for X, y in data_iter(batch_size, features, labels):
    l = loss(net(X, w, b), y).sum()
    # calculate the gradient of batch sample loss
    l.backward()
    # using small batch random gradient descent to iter model parameters
    sgd([w, b], lr, batch_size)
    # reset parameter gradient
    w.grad.data.zero_()
    b.grad.data.zero_()
train_l = loss(net(features, w, b), labels)
print('epoch %d, loss %f' % (epoch + 1, train_l.mean().item()))

print(w, true_w, b, true_b)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值