多变量线性回归

1)目标

使用线性回归,预测房价。自变量有两个,分别为屋子数量和面积。使用这些数据来学习并预测未来某房屋价格。

2)总结

  1. 使用np做矩阵运算时可以时常用assert断言检查矩阵维数是否正确,防止不知名Bug产生。
  2. 设置向量时不要设置成数组型向量,要写成[[x,x2,x3]]这种形式或者将np.array的两个维度写全,避免向量被建立成数组格式,会遭遇无法转置等愚蠢的情况(血的教训)。
import numpy as np
a=np.ones(3)
b=a.T
print(a,'\n',b,)

输出如下,无法转置。
在这里插入图片描述
改成np.ones([1,3])后,

import numpy as np
a=np.ones([1,3])
b=a.T
print(a,'\n',b,)

输出如下,可以成功转置。
在这里插入图片描述

  1. 选择学习率时若学习率过小会发生无法拟合的情况,多次选择学习率,在保证运行效率的同时避免发散。
    图:学习率=0.1683时,梯度上升。
    在这里插入图片描述

3)代码

import numpy as np
import matplotlib.pyplot as plt

#导入数据
data = np.loadtxt('D:\python\homewrok\data_sets\ex1data2.txt', delimiter=",")

x1 = data[:,0]
x2 = data[:,1]
y = data[:,2]

#变量初始化
m = len(data)
n = 3
thetaT = np.zeros((n,1))
aerfa = 0.05
time=0
beilv=max(x1)-min(x1)
JJ=[]
x0=np.ones((m,1))
x1=x1/beilv
x1=x1.reshape(m,1)
x2=x2.reshape(m,1)
x = np.hstack((x0,x1,x2))
JJcost=0
#原函数h
def h(thetaT,x):
    theta = thetaT.reshape(1, n)                        #参数向量转置
    y = theta @ x
    return y

#代价函数
def J(thetaT,x,y):
    theta = thetaT.reshape(1, n)
    J=(h(thetaT,x)-y)**2*(1/2/m)
#主循环
while time<5000:


    JJcost=0
    costT=np.zeros((n,1))                                            #中间向量归零

    for i in range(m):
        xT=x[i].reshape(n,1)
        costT+=(h(thetaT,xT)-y[i])*xT
        JJcost+=(h(thetaT,xT)-y[i])**2
    JJ.append(JJcost[0,0]/2/m)
    thetaT = thetaT - aerfa * costT / m
    time+=1


plt.subplot(211)
plt.plot(range(0,5000),JJ)
plt.show()

print(thetaT,time,beilv)

4)运行结果

分别为theta0,theta1,theta2.
在这里插入图片描述
在这里插入图片描述

4)语法总结

A=np.zeros((3,3))
A=np.zeros_like(B)
data=np.arange(起始值,终值,步长)
data.reshape((4,5))

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值