在这个教程中,我们将学习如何使用 Scikit-Learn 库进行回归分析。回归分析是一种预测连续值的统计方法,常用于预测房价、股票价格等。
安装 Scikit-Learn
首先,确保你已经安装了 Scikit-Learn。如果没有,可以通过以下命令进行安装:
pip install scikit-learn
简单线性回归
简单线性回归是最基本的回归模型,它使用一个自变量来预测一个因变量。
数据准备
import numpy as np
from sklearn.linear_model import LinearRegression
# 创建数据
X = np.array([1, 2, 3, 4, 5]).reshape(-1, 1)
y = np.array([1, 3, 2, 4, 5])
# 创建模型
model = LinearRegression()
# 训练模型
model.fit(X, y)
预测
# 使用模型进行预测
y_pred = model.predict(np.array([6]).reshape(-1, 1))
print(y_pred)
多项式回归
多项式回归可以处理非线性关系。
数据准备
from sklearn.preprocessing import PolynomialFeatures
# 创建多项式特征
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
训练模型
# 创建并训练模型
model_poly = LinearRegression()
model_poly.fit(X_poly, y)
预测
# 使用多项式模型进行预测
y_pred_poly = model_poly.predict(poly.fit_transform(np.array([6]).reshape(-1, 1)))
print(y_pred_poly)
扩展阅读
想要了解更多关于 Scikit-Learn 的内容,可以访问我们的Scikit-Learn 教程页面。
Scikit-Learn Logo