svm支持向量机多分类python代码
时间: 2023-09-08 16:08:29 浏览: 49
可以使用sklearn库中的SVM模型进行多分类,具体实现代码如下:
```python
from sklearn import svm
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载鸢尾花数据集
iris = load_iris()
X = iris.data
y = iris.target
# 将数据集分为训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义SVM模型并进行训练
clf = svm.SVC(kernel='linear', C=1, decision_function_shape='ovr')
clf.fit(X_train, y_train)
# 对测试集进行预测
y_pred = clf.predict(X_test)
print("Accuracy:", accuracy_score(y_test, y_pred))
```
其中,SVM模型中的kernel参数可以选择不同的核函数,C参数用于调节正则化强度,decision_function_shape参数用于解决多分类问题。以上代码实现了使用线性核函数的SVM模型对鸢尾花数据集进行多分类。
相关问题
svm支持向量机分类python代码
以下是一个简单的 SVM 支持向量机分类的 Python 代码示例:
```python
from sklearn import svm
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
# 生成随机数据
X, y = make_blobs(n_samples=50, centers=2, random_state=6)
# 创建 SVM 分类器
clf = svm.SVC(kernel='linear', C=1000)
clf.fit(X, y)
# 绘制决策边界
plt.scatter(X[:, 0], X[:, 1], c=y, s=30, cmap=plt.cm.Paired)
ax = plt.gca()
xlim = ax.get_xlim()
ylim = ax.get_ylim()
# 创建网格来评估模型
xx = np.linspace(xlim[0], xlim[1], 30)
yy = np.linspace(ylim[0], ylim[1], 30)
YY, XX = np.meshgrid(yy, xx)
xy = np.vstack([XX.ravel(), YY.ravel()]).T
Z = clf.decision_function(xy).reshape(XX.shape)
# 绘制决策边界和支持向量
ax.contour(XX, YY, Z, colors='k', levels=[-1, 0, 1], alpha=0.5, linestyles=['--', '-', '--'])
ax.scatter(clf.support_vectors_[:, 0], clf.support_vectors_[:, 1], s=100, linewidth=1, facecolors='none', edgecolors='k')
plt.show()
```
这段代码使用 scikit-learn 库中的 SVM 分类器来对随机生成的数据进行分类,并绘制出决策边界和支持向量。
svm支持向量机做预测python代码
以下是使用Python中的sklearn库实现SVM支持向量机做预测的代码:
```python
# 导入需要的库
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
# 加载数据集
from sklearn.datasets import load_iris
iris = 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=42)
# 使用SVM支持向量机训练模型
clf = svm.SVC(kernel='linear', C=1, gamma='auto')
clf.fit(X_train, y_train)
# 预测测试集数据
y_pred = clf.predict(X_test)
# 计算准确率
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
```
在上面的代码中,我们首先导入了需要的库,并加载了一个经典的数据集——鸢尾花数据集。接着,我们将数据集分为训练集和测试集,并使用SVM支持向量机训练模型。最后,我们使用测试集数据进行预测,并计算准确率。