机器学习:SVM算法(Python)
from sklearn import svm
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_iris
import numpy as np
# 加载鸢尾花数据集
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=666)
# 特征缩放
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# 创建并训练SVM模型
svm_model = svm.SVC(kernel='rbf', C=100, gamma=0.1, probability=True)
svm_model.fit(X_train_scaled, y_train)
# 预测
y_pred = svm_model.predict(X_test_scaled)
# 计算准确率
accuracy = np.mean(y_pred == y_test)
print(f'Accuracy: {accuracy}')
这段代码展示了如何在Python中使用SVM算法进行鸢尾花数据集的分类任务。首先,我们加载了鸢尾花数据集,并将其划分为训练集和测试集。然后,我们对训练集进行了特征缩放,并使用sklearn.svm.SVC
创建并训练了SVM模型。最后,我们使用测试集对模型进行了预测,并计算了模型的准确率。
评论已关闭