【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))
相关推荐
fpcc3 小时前
AI和大模型—神经网络的学习
人工智能·神经网络
乌恩大侠3 小时前
「AI-RAN」Aerial,使用ORAN C1模式
人工智能·5g·spark·o-ru·ai-ran
Zhao-Jichao3 小时前
AI Prompting for Everyone 课程笔记 - 05 使用深度搜索 Using Deep Research
人工智能·笔记
Js.Tx3 小时前
【具体数学 Concrete Mathematics】2.1.5 一般性的方法
算法·具体数学
feasibility.3 小时前
世界模型WSM技术解读:SLAM内化为具身智能的状态记忆,纯RGB机器人导航反超RGB-D
人工智能·机器人·aigc·slam·导航·具身智能·世界模型
alonglong4 小时前
本地模型部署避坑:HF_HOME 缓存指向 + macOS fd 上限 256
人工智能
注塑机数据采集联网4 小时前
数据采集网关入门:ZK-D1/D3从零开始构建你的数据运用
大数据·数据仓库·人工智能·物联网·数据库架构·注塑机网关
hantmac4 小时前
不记得文件名时,Mac 上的搜索还能怎么做?
人工智能·macos
郝学胜-神的一滴4 小时前
游戏设计:原型与开发 18:Unity入门的第一课
人工智能·程序人生·游戏·ui·unity·游戏引擎