from sklearn.datasets import load_wine from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier # 加载葡萄酒数据集 wine = load_wine() # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(wine.data, wine.target, test_size=0.3, random_state=42) # 初始化决策树模型 clf = DecisionTreeClassifier() # 训练模型并预测测试集 clf.fit(X_train, y_train) y_pred = clf.predict(X_test) # 输出准确率 print("7:3的准确率:", clf.score(X_test, y_test)) # 重新划分训练集和测试集,比例为3:1 X_train, X_test, y_train, y_test = train_test_split(wine.data, wine.target, test_size=0.25, random_state=42) # 训练模型并预测测试集 clf.fit(X_train, y_train) y_pred1 = clf.predict(X_test) # 输出准确率 print("3:1的准确率:", clf.score(X_test, y_test)) # 重新划分训练集和测试集,比例为4:1 X_train, X_test, y_train, y_test = train_test_split(wine.data, wine.target, test_size=0.2, random_state=42) # 训练模型并预测测试集 clf.fit(X_train, y_train) y_pred2 = clf.predict(X_test) # 输出准确率 print("4:1的准确率:", clf.score(X_test, y_test)) # 重新划分训练集和测试集,比例为9:1 X_train, X_test, y_train, y_test = train_test_split(wine.data, wine.target, test_size=0.1, random_state=42) # 训练模型并预测测试集 clf.fit(X_train, y_train) y_pred3 = clf.predict(X_test) # 输出准确率 print("9:1的准确率:", clf.score(X_test, y_test))
时间: 2023-08-18 16:16:27 浏览: 114
使用sklearn的cross_val_score进行交叉验证实例
好的,您已经提供了代码来计算每种数据集划分方式的准确率。现在,我会使用 Python 的 Matplotlib 库来绘制折线图,以显示这4种数据集划分方式的准确率。以下是绘制折线图的代码示例:
```python
import matplotlib.pyplot as plt
# 计算每种数据集划分方式的准确率
acc_73 = clf.score(X_test, y_test)
acc_31 = clf.score(X_test, y_test)
acc_41 = clf.score(X_test, y_test)
acc_91 = clf.score(X_test, y_test)
# 绘制折线图
plt.plot([7, 3], [acc_73, acc_73], label="7:3")
plt.plot([3, 1], [acc_31, acc_31], label="3:1")
plt.plot([4, 1], [acc_41, acc_41], label="4:1")
plt.plot([9, 1], [acc_91, acc_91], label="9:1")
# 添加图例和标签
plt.legend()
plt.xlabel("Training set size ratio")
plt.ylabel("Accuracy")
plt.title("Accuracy vs. Training set size ratio")
# 显示折线图
plt.show()
```
这段代码将会绘制一张折线图,其中 x 轴表示训练集和测试集的比例,y 轴表示准确率。每种比例对应一个点,用折线将这些点连接起来,从而形成折线图。图例会显示每个折线所代表的数据集划分方式。
阅读全文