SVM多分类和SVM回归手写代码
时间: 2024-06-10 21:02:00 浏览: 100
SVM多分类:
下面是SVM多分类的手写代码示例,该代码使用了sklearn库中的Iris数据集:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# 加载数据集
iris = datasets.load_iris()
X = iris.data
y = iris.target
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# 训练SVM模型
svm = SVC(kernel='linear', C=1.0)
svm.fit(X_train, y_train)
# 预测并计算准确率
y_pred = svm.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy: ', accuracy)
```
SVM回归:
下面是SVM回归的手写代码示例,该代码使用了sklearn库中的波士顿房价数据集:
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.svm import SVR
from sklearn.metrics import mean_squared_error
# 加载数据集
boston = datasets.load_boston()
X = boston.data
y = boston.target
# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
# 训练SVM回归模型
svm = SVR(kernel='linear', C=1.0, epsilon=0.2)
svm.fit(X_train, y_train)
# 预测并计算均方误差
y_pred = svm.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print('MSE: ', mse)
```
需要注意的是,SVM回归使用的是SVR,而不是SVC。另外,SVM回归需要设置epsilon参数,该参数表示允许的误差范围。
阅读全文