栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

线性回归,梯度下降法,拟合一次函数

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

线性回归,梯度下降法,拟合一次函数

1、生成5阶单位矩阵

import numpy as np

np.identity(5)###任选一种
np.eye(5)

结果为:

[[1. 0. 0. 0. 0.]
 [0. 1. 0. 0. 0.]
 [0. 0. 1. 0. 0.]
 [0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 1.]]

2、获取ex1data1.txt文件数据,生成散点图

import matplotlib.pyplot as plt

data=np.loadtxt(r'D:PYTHONmachine_learningML-homeworkex1-linear regressionex1data1.txt',delimiter=",",dtype="float")####获取ex1data1,
#print(data)
x=data[:,0]
y=data[:,1]
plt.scatter(x,y,marker='x',color='red')   ####画散点图
plt.xlabel('Profit in $10,000s')
plt.ylabel('Population of City in 10,000s')
plt.show()

得出散点图:

3、初始化数据并计算代价函数的值

###初始化数据
X=[np.ones(m),x]
X=np.array(X)
theta=np.zeros(2)
alpha=0.01
iterations=1500##迭代次数
J=0
for a in range(0,m):
    J_1=theta[0]+theta[1]*X[1,a]-y[a]
    print(J_1)
    J_1=J_1*J_1
    J=J+J_1
J=J/2/m

 结果为32.072733877455654

4、梯度下降

代价函数是theta的函数

 

###初始化数据
X=[np.ones(m),x]#####加一列为了方便计算theta[0]+theta[1]*X[1,a]  theta*X
X=np.array(X)
theta=np.zeros(2)
alpha=0.01
iterations=1500##迭代次数

for b in range(0,iterations):
    J=0
    for c in range(0, m):
        J_1 = theta[0] + theta[1] * X[1, c] - y[c]
        J = J + J_1
    theta_0=theta[0]-J/m*alpha
    J = 0
    for c in range(0, m):
        J_1 = (theta[0] + theta[1] * X[1, c] - y[c])*X[1, c]
        J = J + J_1
    theta_1 = theta[1] - J / m * alpha
    theta[0]=theta_0
    theta[1]=theta_1
print(theta)
print(np.matrix(theta).shape)
print(np.matrix([1,3.5]).shape)
print(np.matrix([1,3.5])*np.matrix(theta).T)
print(np.matrix([1,7])*np.matrix(theta).T)

输出结果:

[-3.63029144  1.16636235]
(1, 2)
(1, 2)
[[0.45197679]]
[[4.53424501]]

5、绘制一次函数的图像

J_2=theta[0]+theta[1]*x
plt.plot(x,J_2)
plt.show()

该链接为笔记链接 https://www.notion.so/cd5d8e24c8644d17a54bc29ca3c7999f

由于本人对numpy并不熟练,代码写不不太好,仅供参考

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/844058.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号