线性回归代码
import numpy as npfrom sklearn.linear_model import LinearRegression
import matplotlib.pyplot as plt
# 生成一些示例数据
np.random.seed(0)
X = 2 * np.random.rand(100, 1)
y = 3 + 4 * X + np.random.randn(100, 1)
# 创建线性回归模型
model = LinearRegression()
# 训练模型
model.fit(X, y)
# 打印模型的参数
print("Intercept:", model.intercept_)
print("Coefficient:", model.coef_)
# 预测新数据点
new_X = np.array([]) # 输入一个新的 X 值进行预测
predicted_y = model.predict(new_X)
print("Predicted y:", predicted_y)
# 绘制数据和拟合线
plt.scatter(X, y, color='blue')
plt.plot(X, model.predict(X), color='red')
plt.xlabel('X')
plt.ylabel('y')
plt.title('Linear Regression')
plt.show()
页:
[1]