Write a Python function that performs linear regression using gradient descent. The function should take NumPy arrays X (features with a column of ones for the intercept) and y (target) as input, along with learning rate alpha and the number of iterations, and return the coefficients of the linear regression model as a NumPy array. Round your answer to four decimal places. -0.0 is a valid result for rounding a very small number.
Example:
- Input:
X = np.array([[1, 1], [1, 2], [1, 3]]), y = np.array([1, 2, 3]), alpha = 0.01, iterations = 1000 - Output:
np.array([0.1107, 0.9513])
这道题要求使用梯度下降法来做线性拟合,这个在之前写的《简单线性回归》,已经讲得很清楚了,再来解这道题就变得简单了。
import numpy as np
def gradient(X, y, theta):
m, n = X.shape
inner = X.T @ (X @ theta - y)
return inner / m
def linear_regression_gradient_descent(X: np.ndarray, y: np.ndarray, alpha: float, iterations: int) -> np.ndarray:
# Your code here, make sure to round
m, n = X.shape
theta = np.zeros(n,)
for _ in range(iterations):
theta = theta - alpha * gradient(X, y, theta)
return np.round(theta, 4)
