【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))
相关推荐
2501_920953861 小时前
工业4.0时代,制造企业精益管理咨询的标准化实施步骤
大数据·人工智能·制造
~央千澈~1 小时前
《2026鸿蒙NEXT纯血开发与AI辅助》第四章 对鸿蒙next项目结构目录详解以及实战解决一个最初的依赖安装的报错·卓伊凡
人工智能
xinlianyq2 小时前
2026企业流量破局:四大主流短视频矩阵获客系统深度解析与选型指南
人工智能·矩阵
workflower3 小时前
用硬件换时间”与“用算法降成本”之间的博弈
人工智能·算法·安全·集成测试·无人机·ai编程
Cx330❀4 小时前
一文吃透Linux System V共享内存:原理+实操+避坑指南
大数据·linux·运维·服务器·人工智能
OPHKVPS4 小时前
Anthropic 为 Claude Code 推出“自动模式”:AI 编码工具迈向更高自主性
网络·人工智能·安全·ai
Allen_LVyingbo4 小时前
斯坦福HAI官网完整版《2025 AI Index Report》全面解读
人工智能·数学建模·开源·云计算·知识图谱
金融小师妹4 小时前
基于AI通胀预期建模与能源冲击传导机制的政策分析:高频信号下的风险再评估
人工智能·svn·能源
胡摩西4 小时前
当大模型遇上毫米级定位:机器人将拥有“空间思维”?
人工智能·机器人·slam·gps·室内定位·roomaps