【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))
相关推荐
火山引擎开发者社区1 小时前
漫话火山 Milvus|为 Agent、RAG 、语义搜索而生,AI 时代的极致性价比之选
人工智能
jikemaoshiyanshi7 小时前
AWS 中国峰会 2026 有哪些 AI Agent 相关演讲可以看?按业务、研发与生产阶段选看
大数据·人工智能
网易易盾7 小时前
AI互动产品安全合规体系架构:制度/技术/运营/证据四层落地
人工智能·安全·aigc·内容安全
wabs6667 小时前
关于图论【卡码网117.软件构建的思考】
数据结构·算法·软件构建·图论·卡码网
新知图书7 小时前
4.3 链接速读
人工智能·语音识别·ai助手·千问
江苏久众新视8 小时前
SOP-AI实战:基于AI视觉与视频检测,精准管控空调管件装配防漏防错
人工智能
mifengxing8 小时前
LeetCode 41.缺失的第一个正数|Hard题O(n)+O(1)最优解法深度解析
java·算法·leetcode·排序算法
Tongzhi20268 小时前
从部署到运维:通芝科技无感考勤一体机的全流程效率解析
运维·数据结构·科技·算法·贪心算法
Wang's Blog8 小时前
AI Agent白手起家30: 动态示例选择器之根据长度选择 Few Shot 示例
算法
u0103055279 小时前
Java AWT鼠标事件全解析
人工智能·1024程序员节