基于SVM的预测波士顿房价
时间: 2023-07-26 10:24:47 浏览: 119
好的,我可以为你提供一个基于SVM的波士顿房价预测代码。首先,我们需要导入必要的库:
```python
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error
```
然后,我们加载波士顿房价数据集,并将数据集划分为训练集和测试集:
```python
boston_data = load_boston()
X = boston_data.data
y = boston_data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
接下来,我们对数据集进行标准化处理:
```python
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
```
然后,我们使用支持向量回归(SVR)算法来训练模型:
```python
clf = SVR(kernel='linear')
clf.fit(X_train, y_train)
```
最后,我们使用测试集来评估模型的均方误差:
```python
y_pred = clf.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
```
完整的代码如下:
```python
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error
boston_data = load_boston()
X = boston_data.data
y = boston_data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train = scaler.fit_transform(X_train)
X_test = scaler.transform(X_test)
clf = SVR(kernel='linear')
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print("Mean Squared Error:", mse)
```
这个代码可以用于预测波士顿房价,你也可以尝试使用其他数据集和算法。
阅读全文