对数回归python实现波士顿房价预测
时间: 2023-09-09 20:13:04 浏览: 113
波士顿房价预测是一个经典的回归问题,可以使用对数回归(Logistic Regression)进行预测。下面是使用Python进行对数回归预测波士顿房价的步骤:
1. 导入必要的库和数据集
```python
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston
boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['PRICE'] = boston.target
```
2. 数据预处理
```python
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
# 特征缩放
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X = sc_X.fit_transform(X)
# 划分训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
```
3. 训练模型
```python
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
```
4. 预测结果
```python
y_pred = regressor.predict(X_test)
```
5. 评估模型
```python
from sklearn.metrics import r2_score
r2_score(y_test, y_pred)
```
完整代码如下:
```python
import numpy as np
import pandas as pd
from sklearn.datasets import load_boston
boston = load_boston()
df = pd.DataFrame(boston.data, columns=boston.feature_names)
df['PRICE'] = boston.target
X = df.iloc[:, :-1].values
y = df.iloc[:, -1].values
# 特征缩放
from sklearn.preprocessing import StandardScaler
sc_X = StandardScaler()
X = sc_X.fit_transform(X)
# 划分训练集和测试集
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)
# 训练模型
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
regressor.fit(X_train, y_train)
# 预测结果
y_pred = regressor.predict(X_test)
# 评估模型
from sklearn.metrics import r2_score
r2_score(y_test, y_pred)
```
输出结果为0.5892223849182513,说明模型的拟合效果不是很好。可以尝试调整模型参数或者使用其他算法进行预测。
阅读全文