我制作了一个使用numpy进行线性回归的python脚本。 当我运行它们时,出现以下错误:
警告(来自警告模块): 文件“ C:\ Users \ Moham \ Desktop \ Simple linear equation.py”,第27行 gradient_sum_squares + =梯度** 2 RuntimeWarning:在double_scalars中遇到溢出
对于出现问题的任何帮助,我们将不胜感激。
代码如下:
import numpy as np
import pandas as pd
from math import sqrt
df = pd.read_csv('Boston.csv')
def simple_linear_regression(x_points, y_points, step_size=0.01, tolerance=0.001, max_iter=1000):
converged = False
coefficients = np.random.rand(2)
y = np.array(y_points)
X = np.ones((len(x_points), 2))
X[:, 1] = x_points
iteration = 0
while not converged:
if iteration >= max_iter:
return coefficients
predictions = np.dot(X, coefficients)
residual = y - predictions
gradient_sum_squares = 0
for i in range(len(coefficients)):
gradient = np.dot(2, np.dot(X[:, i], residual))
gradient_sum_squares += gradient ** 2
coefficients[i] = coefficients[i] - np.dot(step_size, gradient)
if sqrt(gradient_sum_squares) < tolerance:
converged = True
iteration += 1
return coefficients
print(simple_linear_regression(df["TV"], df["sales"]))