【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))
相关推荐
深圳佛手5 分钟前
jupyter notebook如何使用虚拟环境?
人工智能·python
Mintopia7 分钟前
⚙️ WebAssembly在AIGC推理中的优化细节
人工智能·llm·trae
Mintopia11 分钟前
🌐 WebAIGC的技术普惠:降低创作门槛还是加剧数字鸿沟?
人工智能·aigc
白日做梦Q12 分钟前
少样本学习(Few-Shot Learning):让AI学会“举一反三”的图像分类新范式
人工智能
mit6.82414 分钟前
hash+presum判等|幻方0
算法
码上掘金15 分钟前
基于YOLO和大语言模型的PCB智能缺陷检测系统
人工智能·yolo·语言模型
萌>__<新32 分钟前
力扣打卡每日一题————最小覆盖子串
数据结构·算法·leetcode·滑动窗口·哈希表
裤裤兔1 小时前
卷积神经网络中的自适应池化
人工智能·神经网络·cnn·自适应池化
ada7_1 小时前
LeetCode(python)230.二叉搜索树中第k小的元素
python·算法·leetcode·链表
TracyCoder1231 小时前
词嵌入来龙去脉:One-hot、Word2Vec、GloVe、ELMo
人工智能·自然语言处理·word2vec