【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))
相关推荐
Lethehong19 分钟前
openEuler AI 图像处理:Stable Diffusion CPU 推理性能优化与评测
人工智能
MicroTech202520 分钟前
MLGO微算法科技发布突破性运动想象脑机接口算法,高精度与低复杂度兼得
科技·算法
Guheyunyi23 分钟前
智慧停车管理系统:以科技重塑交通效率与体验
大数据·服务器·人工智能·科技·安全·生活
std8602124 分钟前
微软将允许用户从Windows 11文件资源管理器中移除“AI 动作”入口
人工智能·microsoft
为爱停留26 分钟前
Spring AI实现MCP(Model Context Protocol)详解与实践
java·人工智能·spring
秋刀鱼 ..26 分钟前
第七届国际科技创新学术交流大会暨机械工程与自动化国际学术会议(MEA 2025)
运维·人工智能·python·科技·机器人·自动化
cici1587428 分钟前
基于不同算法的数字图像修复Matlab实现
算法·计算机视觉·matlab
学历真的很重要7 小时前
VsCode+Roo Code+Gemini 2.5 Pro+Gemini Balance AI辅助编程环境搭建(理论上通过多个Api Key负载均衡达到无限免费Gemini 2.5 Pro)
前端·人工智能·vscode·后端·语言模型·负载均衡·ai编程
普通网友7 小时前
微服务注册中心与负载均衡实战精要,微软 2025 年 8 月更新:对固态硬盘与电脑功能有哪些潜在的影响。
人工智能·ai智能体·技术问答
苍何7 小时前
一人手搓!AI 漫剧从0到1详细教程
人工智能