2021-02-24

梯度下降算法-python实现

曲线拟合:

数据集

from numpy import *
import numpy as np
# 数据集大小 即20个数据点
m = 20
# x的坐标以及对应的矩阵
X0 = ones((m, 1))  # 生成一个m行1列的向量,也就是x0,全是1
X1 = arange(1, m+1).reshape(m, 1)  # 生成一个m行1列的向量,也就是x1,从1到m
X = hstack((X0, X1))  # 按照列堆叠形成数组,其实就是样本数据
# 对应的y坐标
y = np.array([
    3, 4, 5, 5, 2, 4, 7, 8, 11, 8, 12,
    11, 13, 13, 16, 17, 18, 17, 19, 21
]).reshape(m, 1)
# 学习率
alpha = 0.01

注:hstack()为数组合并,X,y都为列向量相互

求代价函数和代价函数的梯度

def cost_function(theta, X, Y):
    cost1=np.dot(X,theta)-Y
    cost2=cost1.transpose()
    return 1/2/m*np.dot(cost2,cost1)
def gradient(theta, X, Y):
    cost1=np.dot(X,theta)-Y
    return 1/m*np.dot(X.transpose(),cost1)

梯度下降求解

def gradient_descent(X,Y,theta):
    gradient2=gradient(theta, X, Y)
    while not all (abs(gradient2)  <= 1e-5):
        theta=theta-alpha*gradient2
        gradient2 = gradient(theta, X, Y)
    return theta
theta=np.array([[1],[1]]).reshape((-1,1))
theta=gradient_descent(X, y, theta)
cost_function(theta, X, y)

绘制图像

from matplotlib import pyplot as plt
x = arange(0, 21, 0.2)  # x的范围
Y = theta[0] + theta[1]*x
plt.plot(x, Y)
plt.scatter(X1,y,c='#00CED1')
plt.show()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值