【Deep-ML系列】Linear Regression Using Gradient Descent(手写梯度下降)

题目链接:Deep-ML

这道题主要是要考虑矩阵乘法的维度,保证维度正确,就可以获得最终的theata

python 复制代码
import numpy as np
def linear_regression_gradient_descent(X: np.ndarray, y: np.ndarray, alpha: float, iterations: int) -> np.ndarray:
    """
    Linear regression
    :param X: m * n
    :param y:
    :param alpha:
    :param iterations:
    :return:
    """
    m, n = X.shape
    theta = np.zeros((n, 1))
    y = y.reshape(m, 1)     # 保证y是列向量
    for i in range(iterations):
        prediction = np.dot(X, theta)   # m * 1
        error = prediction - y          # m * 1
        gradient = np.dot(X.T, error)   # n * 1
        theta = theta - alpha * (1 / m) * gradient
    theta = np.round(theta, decimals=4)
    return theta

if __name__ == '__main__':
    X = np.array([[1, 1], [1, 2], [1, 3]])
    y = np.array([1, 2, 3])
    alpha = 0.01
    iterations = 1000
    print(linear_regression_gradient_descent(X, y, alpha, iterations))
相关推荐
学嵌入式的小杨同学几秒前
顺序表(SqList)完整解析与实现(数据结构专栏版)
c++·算法·unity·游戏引擎·代理模式
jishijun204几秒前
语音输入新选择:Handy - 注重隐私的离线语音转文本工具
人工智能
格林威1 分钟前
多光源条件下图像一致性校正:消除阴影与高光干扰的 6 个核心策略,附 OpenCV+Halcon 实战代码!
人工智能·数码相机·opencv·算法·计算机视觉·分类·视觉检测
摆烂咸鱼~1 分钟前
机器学习(14)
人工智能·机器学习
iAkuya3 分钟前
(leetcode)力扣100 40二叉树的直径(迭代递归)
java·算法·leetcode
小爷毛毛_卓寿杰6 分钟前
修复 Xinference + vLLM 启动失败:0 bytes read 错误的真实原因与解决方案
人工智能
橘颂TA8 分钟前
【剑斩OFFER】算法的暴力美学——leetCode 103 题:二叉树的锯齿形层序遍历
算法·leetcode·结构与算法
2501_901147839 分钟前
高性能计算笔记:灯泡开关问题的数学优化与常数级解法
笔记·算法·求职招聘
田井中律.9 分钟前
知识图谱(一)
人工智能·知识图谱
C_心欲无痕10 分钟前
JavaScript 常见算法与手写函数实现
开发语言·javascript·算法