NN:最小二乘法与梯度下降法的Python实现

NN:最小二乘法与梯度下降法的Python实现

说明:仅为个人学习笔记,请适量参考。代码是参考其他博主修改而来,因为忘记收藏了所以不放连接了。

最小二乘法

# least square error 最小二乘法
# 理论上最小二乘法可以拟合任何函数
# 使用不同的拟合方法可以拟合不同的函数类型,采用了线性回归的方法拟合了一条曲线
class least_square_error():
    def __init__(self, n):
        self.w = 0
        self.b = 0
        self.n = n

    def Adjust(self):
        # 需要拟合的线性直线
        # line = self.w * self.n[0] + self.b * self.n[1]
        # print(self.n)
        # 求偏导,列方程,求解
        # 也算是求梯度了
        if len(self.n) == 2:
            sx = 0.5 * (self.n[0][0] + self.n[0][1]) * (self.n[0][1] - self.n[0][0] + 1)
            sx2 = (self.n[0][1] * (self.n[0][1] + 1) * (2 * self.n[0][1] + 1) - self.n[0][0] * (self.n[0][1] - 1) * (2 * self.n[0][0] - 1)) / 6
        else:
            # print(self.n[:, 0])
            sx = sum(self.n[:, 0])
            sx2 = sum(self.n[:, 0] * self.n[:, 0])
            ex = sx / len(self.n)

        sxy = sum(self.n[:, 0] * self.n[:, 1])
        ey = np.mean(self.n[:, 1])

        self.w = (sxy - ey * sx) / (sx2 - ex * sx)
        self.b = (ey * sx2 - sxy * ex) / (sx2 - ex * sx)
        return self.w,  self.b

# 随机生成整数
x = np.arange(25)
# 产生数据点
y = x*15+20+np.random.randn(len(x))*5
# 绘制数据集散点图
plt.scatter(x,y)
# 转换为列表
n = [list(t) for t in zip(x, y)]
# 转换为数组方便使用切片
n = np.array(n)

# 进行预测
SE = least_square_error(n)
w, b = SE.Adjust()

print(w, b)
plt.plot(x,w*x+b)
plt.show()

在这里插入图片描述

梯度下降法

# 梯度下降法
class gradient_descent():
    def __init__(self,m):
        self.m = m

    # 输入数据点集和迭代初值
    def cost_function(self, x, y, theta):
        # 计算误差
        # np.dot()矩阵的乘法
        diff = np.dot(x, theta) - y
        # 返回代价函数的值
        # np.transpose()转置
        return (1 / (2 * self.m)) * np.dot(diff.transpose(), diff)

    def gradient_function(self, x, y, theta):
        diff = np.dot(x, theta) - y
        # 这里一开始搞错了,变成了误差与数据相乘
        return (1 / self.m) * np.dot(x.transpose(), diff)


    # 使用平方差损失函数
    # 输入数据点集和学习率,返回线性w,b
    def gradient_descent(self, x, y, alpha):
        # print(x)
        # print(y)
        # 梯度下降的起点
        theta = np.array([1, 1]).reshape(2, 1)
        # 计算梯度
        gradient = self.gradient_function(x, y, theta)
        # all()当参数内所有的值都为True或者都为空时返回True
        while not all(abs(gradient) <= 1e-5):
            print("gradient:", abs(gradient))
            theta = theta - alpha * gradient
            gradient = self.gradient_function(x, y, theta)
        return theta

    # 根据数据画出对应的图像
    def plot(self, X, Y, theta):
        ax = plt.subplot(111)  # 这是我改的
        ax.scatter(X, Y, s=30, c="red", marker="s")
        plt.xlabel("X")
        plt.ylabel("Y")
        x = np.arange(0, 21, 0.2)  # x的范围
        y = theta[0] + theta[1]*x
        ax.plot(x, y)
        plt.show()

# 数据集大小 即20个数据点
m = 20
# x的坐标以及对应的矩阵
X0 = np.ones((m, 1))  # 生成一个m行1列的向量,也就是x0,全是1
X1 = np.arange(1, m+1).reshape(m, 1)  # 生成一个m行1列的向量,也就是x1,从1到m
X = np.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

GD = gradient_descent(m= m)
optimal = GD.gradient_descent(X, Y, alpha)

print('optimal:', optimal)
print('cost function:', GD.cost_function(X, Y, optimal)[0][0])
GD.plot(X1, Y, optimal)

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Ydon?tkwhmeIS

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

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

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

打赏作者

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

抵扣说明:

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

余额充值