混淆矩阵决策树预测值真实值代码
时间: 2023-07-09 18:24:52 浏览: 43
你可以使用 `sklearn.metrics` 中的 `confusion_matrix` 函数来绘制混淆矩阵,示例如下:
``` python
from sklearn.metrics import confusion_matrix
# 对测试数据进行预测
y_pred = clf.predict(X_test)
# 计算混淆矩阵
cm = confusion_matrix(y_test, y_pred)
# 打印混淆矩阵
print(cm)
```
其中,`confusion_matrix` 函数的参数为真实标签 `y_test` 和预测标签 `y_pred`。函数的返回值为混淆矩阵。你可以通过打印混淆矩阵来查看分类器的性能。
混淆矩阵的形式如下:
| | 预测值为正例 | 预测值为反例 |
| :----------:| :----------: | :----------: |
| 实际值为正例 | TP | FN |
| 实际值为反例 | FP | TN |
其中,TP 表示真正例,即分类器将正例正确分类的样本数;FN 表示假反例,即分类器将正例错误分类为反例的样本数;FP 表示假正例,即分类器将反例错误分类为正例的样本数;TN 表示真反例,即分类器将反例正确分类的样本数。
相关问题
决策树预测值真实值散点图代码
以下是一个示例代码,它使用 `scatter` 函数绘制决策树预测值和真实值的散点图:
```python
from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
# 加载数据集
iris = load_iris()
X = iris.data[:, 2:] # 取花瓣长度和宽度两个特征
y = iris.target
# 训练决策树模型
tree_clf = DecisionTreeClassifier(max_depth=2)
tree_clf.fit(X, y)
# 预测样本标签
y_pred = tree_clf.predict(X)
# 绘制散点图
plt.scatter(y, y_pred)
plt.xlabel('True Label')
plt.ylabel('Predicted Label')
plt.show()
```
这段代码首先训练了一个决策树模型,并使用训练数据集 `X` 对其进行预测,得到预测结果 `y_pred`。然后使用 `scatter` 函数绘制散点图,其中 `x` 参数表示真实值,`y` 参数表示预测值。这样可以通过散点图来观察预测值和真实值之间的关系,以评估决策树模型的性能。
决策树对预测值和真实值做散点图代码
以下是使用Python代码绘制决策树预测值和真实值的散点图的示例:
```python
import matplotlib.pyplot as plt
import numpy as np
from sklearn.tree import DecisionTreeRegressor
# 训练数据集
X_train = np.array([[1], [2], [3], [4], [5], [6], [7], [8], [9], [10]])
y_train = np.array([2, 4, 6, 8, 10, 12, 14, 16, 18, 20])
# 测试数据集
X_test = np.array([[0.5], [1.5], [2.5], [3.5], [4.5], [5.5], [6.5], [7.5], [8.5], [9.5]])
# 创建决策树模型
tree = DecisionTreeRegressor(max_depth=2)
tree.fit(X_train, y_train)
# 对测试数据进行预测
y_pred = tree.predict(X_test)
# 绘制散点图
plt.scatter(X_test, y_pred, color='red', label='Predicted Values')
plt.scatter(X_test, tree.predict(X_test), color='blue', label='True Values')
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Decision Tree Regression')
plt.legend()
plt.show()
```
在这个示例中,我们使用了一个简单的训练数据集和测试数据集来创建和测试决策树回归模型。我们使用matplotlib库中的scatter函数来绘制散点图,其中红色点代表模型预测的值,蓝色点代表真实的值。通过比较这两组点的位置和分布,我们可以直观地看出模型的预测效果和准确性。