【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))
相关推荐
SmartBrain1 分钟前
FastAPI实战(第三部分):浏览历史的接口开发详解
数据库·人工智能·aigc·fastapi
skywalk81637 分钟前
解决opencode报错:Error: Failed to spawn OpenCode Server
人工智能
Navigator_Z7 分钟前
LeetCode //C - 962. Maximum Width Ramp
c语言·算法·leetcode
m0_672703318 分钟前
上机练习第29天
算法
兩尛10 分钟前
409. 最长回文串
c++·算法·leetcode
(❁´◡`❁)Jimmy(❁´◡`❁)12 分钟前
【KMP】算法详解
算法
智者知已应修善业23 分钟前
【pta反转加法构造回文数c语言1000位】2025-1-31
c语言·c++·经验分享·笔记·算法
List<String> error_P23 分钟前
蓝桥杯基础知识点:模拟-数位操作类题目
python·算法·蓝桥杯
极客先躯41 分钟前
高级java每日一道面试题-2025年7月15日-基础篇[LangChain4j]-如何集成国产大模型(如通义千问、文心一言、智谱 AI)?
java·人工智能·langchain·文心一言·异常处理·密钥管理·参数调优
阿星AI工作室1 小时前
我搭了一个 AI 写作机器人,每天自动写文章发到公众号草稿箱
人工智能·程序员