Python一元线性回归代码:# 导入必要的库
Python一元线性回归代码:
# 导入必要的库
import numpy as np
import matplotlib.pyplot as plt
# 设置训练数据
x_train = np.array([1,2,3,4,5])
y_train = np.array([2,4,6,8,10])
# 计算权重和偏差
n_samples = x_train.shape[0]
w = (np.sum(x_train * y_train) - n_samples * np.mean(x_train) * np.mean(y_train)) / (np.sum(x_train ** 2) - n_samples * np.mean(x_train) ** 2)
b = np.mean(y_train) - w * np.mean(x_train)
# 画出拟合曲线
plt.plot(x_train, y_train, 'o', label='$(\\hat x^{(i)},\\hat y^{(i)})$')
x = np.linspace(0, 6, 1000)
y = w * x + b
plt.plot(x, y, label='$y = wx + b$')
plt.legend()
plt.show()
本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处
评论列表(71条)