from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn import svm

# 导入iris数据
iris = datasets.load_iris()

# 将数据分为训练集与测试集,测试集占30%
X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.3, random_state=0)

# 在训练集上训练
for C in [1, 10, 100, 1000]:
    # 使用支持机对iris数据举行分类拟合
    clf = svm.SVC(kernel='linear', C=C)
    clf.fit(X_train, y_train)

    # 分别给出其在训练数据以及测试数据上的准确率
    print('Accuracy on training data with C={}: {:.2f}'.format(C, clf.score(X_train, y_train)))
    print('Accuracy on testing data with C={}: {:.2f}'.format(C, clf.score(X_test, y_test)))

# 使用支持向量机对训练数据拟合
# 使用线性核函数
clf = svm.SVC(kernel='linear')
clf.fit(X_train, y_train)

# 给出支持向量
support_vectors = clf.support_vectors_
# 给出支持向量的索引值
support_vector_indices = clf.support_
# 给出每个类中的支持向量个数
support_vectors_per_class = clf.n_support_
# 给出支持向量机中的 w 的值
w = clf.coef_
# 给出支持向量机中的 b 的值
b = clf.intercept_

# 打印结果
print('Support Vectors:')
print(support_vectors)
print('Indices of support vectors:', support_vector_indices)
print('Number of support vectors for each class:', support_vectors_per_class)
print('Coefficients of the support vector machine:', w)
print('Intercept of the support vector machine:', b)
Python 使用支持向量机(SVM)对 Iris 数据集进行分类

原文地址: https://www.cveoy.top/t/topic/kKSI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录