一元线性回归的python实现:单因素的波士顿房价预测

利用一元线性回归的解析解公式:

w=\frac{\sum_{1}^{n}(x_{i}-\bar{x})(y_{i}-\bar{y})}{\sum_{1}^{n}(x_{i}-\bar{x})^{2}}

b=\bar{y}-w\bar{x}

数据来源于tensorflow.keras的内置数据集boston_housing,通过切片只取平均房间数作为自变量,利用tensorflow进行矩阵运算。

版本一如下:

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

def weight(x,y):
    x_mean=tf.reduce_mean(x,0)
    y_mean=tf.reduce_mean(y,0)
    n=len(x)
    i=1
    fenzi=0
    fenmu=0
    while i<=n:
        fenzi=fenzi+(x[i-1]-x_mean)*(y[i-1]-y_mean)
        fenmu=fenmu+(x[i-1]-x_mean)**2
        i=i+1
    weight=fenzi/fenmu
    return weight

def bias(x,y,w):
    x_mean=tf.reduce_mean(x,0)
    y_mean=tf.reduce_mean(y,0)
    bias=y_mean-w*x_mean
    return bias

#main

boston_housing=tf.keras.datasets.boston_housing
(train_x,train_y),(test_x,test_y)=boston_housing.load_data(test_split=0)
room=train_x[:,5]

w=weight(room,train_y)
b=bias(room,train_y,w)

print("拟合结果 w=%f,b=%f" % (w,b))

y_pred=tf.constant(w*room+b)

plt.rcParams["font.sans-serif"]="SimHei"

plt.figure()
plt.scatter(room,train_y,color="red",s=2,label="原始数据")
plt.scatter(room,y_pred,color="blue",s=2,label="预测房价")
plt.plot(room,y_pred,label="拟合曲线")

plt.xlabel("平均房间数")
plt.ylabel("房价")

plt.xlim(2.5,10)

plt.suptitle("一元线性回归波士顿房价预测" ,fontsize=17)

plt.legend()
plt.show()

后来发现可以利用对矩阵中元素求和来代替函数weight( )里的循环算法,于是对这个函数的定义作了调整:

def weight(x,y):
    x_mean=tf.reduce_mean(x,0)
    y_mean=tf.reduce_mean(y,0)
    n=len(x)
    i=1
    fenzi=tf.reduce_sum((x-x_mean)*(y-y_mean))
    fenmu=tf.reduce_sum(pow((x-x_mean),2))
    weight=fenzi/fenmu
    return weight

输出结果如下

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张向南zhangxn

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值