构建一个预测模型。sklearn fit ,用最相关的特征10个来预测。尝试用linear regression.
时间: 2024-10-27 13:07:44 浏览: 13
LogisticRegression逻辑回归模型_逻辑回归_信用预测_
5星 · 资源好评率100%
构建一个预测模型通常涉及以下几个步骤,这里以Python的scikit-learn库为例,使用线性回归(Linear Regression)作为示例:
1. 导入所需库和数据集:
```python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.feature_selection import SelectKBest, f_regression
from sklearn.metrics import mean_squared_error
# 加载数据,假设df是DataFrame格式的数据
df = pd.read_csv('your_data.csv') # 替换为实际文件路径
```
2. 数据预处理:
```python
X = df.drop('target_column', axis=1) # 'target_column'是你想要预测的目标变量
y = df['target_column']
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
3. 特征选择(取10个最相关特征):
```python
selector = SelectKBest(score_func=f_regression, k=10)
X_train_selected = selector.fit_transform(X_train, y_train)
X_test_selected = selector.transform(X_test)
```
4. 训练线性回归模型:
```python
model = LinearRegression()
model.fit(X_train_selected, y_train)
```
5. 预测并评估模型性能:
```python
y_pred = model.predict(X_test_selected)
mse = mean_squared_error(y_test, y_pred)
print(f"Mean Squared Error (MSE): {mse}")
```
阅读全文