用python实现回归建模
时间: 2023-09-24 20:07:36 浏览: 67
以下是使用Python实现回归建模的示例代码:
1. 线性回归模型
```
# 导入必要的库
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
# 读取数据
data = pd.read_csv('data.csv')
# 分离特征和目标变量
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
# 创建线性回归模型
model = LinearRegression()
# 拟合模型
model.fit(X, y)
# 预测
y_pred = model.predict(X)
# 打印模型参数
print('Coefficients: ', model.coef_)
print('Intercept: ', model.intercept_)
print('R-squared: ', model.score(X, y))
```
2. 多项式回归模型
```
# 导入必要的库
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures
# 读取数据
data = pd.read_csv('data.csv')
# 分离特征和目标变量
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
# 创建多项式特征
poly = PolynomialFeatures(degree=2)
X_poly = poly.fit_transform(X)
# 创建多项式回归模型
model = LinearRegression()
# 拟合模型
model.fit(X_poly, y)
# 预测
y_pred = model.predict(X_poly)
# 打印模型参数
print('Coefficients: ', model.coef_)
print('Intercept: ', model.intercept_)
print('R-squared: ', model.score(X_poly, y))
```
3. 决策树回归模型
```
# 导入必要的库
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeRegressor
# 读取数据
data = pd.read_csv('data.csv')
# 分离特征和目标变量
X = data.iloc[:, :-1].values
y = data.iloc[:, -1].values
# 创建决策树回归模型
model = DecisionTreeRegressor(random_state=0)
# 拟合模型
model.fit(X, y)
# 预测
y_pred = model.predict(X)
# 打印模型参数
print('R-squared: ', model.score(X, y))
```
阅读全文