采用 scikit-learn 中的线性 SVM 对 iris 数据集进行二分类
时间: 2024-02-11 19:03:40 浏览: 100
S_SVM.zip_SVM_SVM Iris_SVM分类_matlab svm iris_数据分类
好的,我会为您提供一个 Python 代码示例,使用 scikit-learn 中的线性 SVM 对 iris 数据集进行二分类。首先,我们需要导入所需的库和数据集:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score
iris = load_iris()
X = iris.data[:, :2]
y = iris.target
```
在这里,我们只选择了 iris 数据集的前两个特征,因为我们希望将其可视化。接下来,我们将数据分为训练集和测试集:
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
然后,我们可以使用 LinearSVC 模型拟合数据:
```python
clf = LinearSVC(random_state=42)
clf.fit(X_train, y_train)
```
最后,我们可以使用测试集评估模型的表现:
```python
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
完整代码如下:
```python
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.svm import LinearSVC
from sklearn.metrics import accuracy_score
iris = load_iris()
X = iris.data[:, :2]
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
clf = LinearSVC(random_state=42)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('Accuracy:', accuracy)
```
运行代码后,您将得到一个准确率。希望这个示例能够帮助您理解如何使用线性 SVM 对 iris 数据集进行二分类。
阅读全文