使用随机梯度下降(SGD)的支持向量机(SVM)相比于不使用SGD的SVM,具有以下优势:
下面是使用scikit-learn库中的SGDClassifier来实现SGD-SVM的示例代码:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import SGDClassifier
from sklearn.svm import SVC
from sklearn.metrics import accuracy_score
# 加载数据集
data = load_iris()
X, y = data.data, data.target
# 数据预处理
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, test_size=0.2, random_state=42)
# 使用SGD-SVM训练模型
sgd_svm = SGDClassifier(loss='hinge', alpha=0.01, max_iter=1000, random_state=42)
sgd_svm.fit(X_train, y_train)
# 使用SVM训练模型
svm = SVC(kernel='linear', random_state=42)
svm.fit(X_train, y_train)
# 在测试集上评估模型性能
y_pred_sgd = sgd_svm.predict(X_test)
y_pred_svm = svm.predict(X_test)
accuracy_sgd = accuracy_score(y_test, y_pred_sgd)
accuracy_svm = accuracy_score(y_test, y_pred_svm)
print("SGD-SVM准确率:", accuracy_sgd)
print("SVM准确率:", accuracy_svm)
在以上示例中,我们使用了鸢尾花数据集(iris dataset),对其进行了数据预处理和训练集/测试集划分。然后分别使用SGD-SVM和SVM训练模型,并在测试集上评估了两者的准确率。最后打印出了SGD-SVM和SVM的准确率。
需要注意的是,SGD-SVM的参数(如loss、alpha、max_iter等)需要根据具体问题进行调整,以获得更好的性能。