【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))
相关推荐
不爱土豆唯爱马铃薯2 分钟前
MC-026 | 实战·用MonkeyCode开发论文辅助工具
人工智能
程序员cxuan5 分钟前
姚顺雨这次访谈,腾讯终于把 AI 下半场讲明白了
人工智能·后端·程序员
甲维斯1 小时前
Claude Code中文界面版更一波!又改了5000+行!
人工智能·ai编程
腾讯云开发者1 小时前
从前沿洞见到落地实践:腾讯云TVP布道澳门,燃动AI Agent新思潮
人工智能
雪隐1 小时前
个人电脑玩AI-02让5060 Ti给你打工——Whisper语音识别篇(下)
人工智能·后端
HIT_Weston1 小时前
110、【Agent】【OpenCode】todowrite 工具提示词(示例)(四)
人工智能·agent·opencode
Zhang~Ling1 小时前
C++ 红黑树封装:myset和mymap的底层实现
开发语言·数据结构·c++·算法
ECT-OS-JiuHuaShan1 小时前
什么是对和错?——“有针对性定义域的逻辑值的真伪”:认识论终极追问的公理化裁决
数据库·人工智能·算法·机器学习·数学建模
澹锦汐1 小时前
从 0 到 1 构建 AI 创意工具:独立开发者的 LLM 应用实战
人工智能