import seaborn as sns import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix # Example data y_true = [0, 1, 0, 1, 0, 1, 0, 0, 1, 1] y_pred = [0, 0, 0, 1, 0, 1, 1, 0, 1, 0] # Calculate confusion matrix cm = confusion_matrix(y_true, y_pred) # Plot heatmap sns.heatmap(cm, annot=True, cmap='Blues') plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.show()上述代码中的y_true,y_pred,如何传入自己训练的真实值预测值标签

时间: 2023-09-21 10:08:16 浏览: 53
如果你有自己的训练数据和模型,可以将其预测结果与真实标签分别存储为两个数组,然后将这两个数组传入 `confusion_matrix` 函数中即可得到混淆矩阵。下面是一个示例代码: ```python import seaborn as sns import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix # 假设你的真实标签为 y_true,预测标签为 y_pred y_true = [...] # 真实标签数组 y_pred = [...] # 预测标签数组 # 计算混淆矩阵 cm = confusion_matrix(y_true, y_pred) # 绘制热力图 sns.heatmap(cm, annot=True, cmap='Blues') plt.xlabel('Predicted labels') plt.ylabel('True labels') plt.show() ``` 其中,`y_true` 和 `y_pred` 分别代表真实标签和预测标签的数组,你需要将它们替换为自己的数据即可。注意,这两个数组的长度必须相等。
相关问题

将后面代码绘制的图保存的代码from sklearn.metrics import confusion_matrix import seaborn as sns import matplotlib.pyplot as plt # 预测结果和真实结果 y_true = [0, 1, 2, 0, 1, 2, 0, 1, 2] y_pred = [0, 1, 1, 0, 2, 1, 0, 2, 2] # 计算混淆矩阵 cm = confusion_matrix(y_true, y_pred) # 可视化混淆矩阵 sns.set() sns.heatmap(cm, annot=True, cmap='Blues') plt.xlabel('Predicted label') plt.ylabel('True label') plt.show()

以下是将代码中绘制的图保存到本地的代码: ```python from sklearn.metrics import confusion_matrix import seaborn as sns import matplotlib.pyplot as plt # 预测结果和真实结果 y_true = [0, 1, 2, 0, 1, 2, 0, 1, 2] y_pred = [0, 1, 1, 0, 2, 1, 0, 2, 2] # 计算混淆矩阵 cm = confusion_matrix(y_true, y_pred) # 可视化混淆矩阵 sns.set() sns.heatmap(cm, annot=True, cmap='Blues') plt.xlabel('Predicted label') plt.ylabel('True label') plt.savefig('confusion_matrix.png') plt.show() ``` 这段代码会将绘制的混淆矩阵保存为当前工作路径下的 `confusion_matrix.png` 文件。您可以根据需要修改文件名和路径。

import pandas as pd import numpy as np import scipy.stats as stats import seaborn as sns from sklearn.metrics import RocCurveDisplay from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix,accuracy_score from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn import tree from sklearn.decomposition import PCA import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeClassifier请在此基础上续写代码块,要求是(1) 读入数据后,选取自变量"sysBP", "diaBP","age","totChol","BMI", "heartRate", "glucose"记为X,因变量"TenYearCHD"记为y,组成新的数据集。¶

import pandas as pd import numpy as np import scipy.stats as stats import seaborn as sns from sklearn.metrics import RocCurveDisplay from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix,accuracy_score from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn import tree from sklearn.decomposition import PCA import matplotlib.pyplot as plt from sklearn.tree import DecisionTreeClassifier # 读入数据 data = pd.read_csv("heart.csv") # 选取自变量 X = data[["sysBP", "diaBP", "age", "totChol", "BMI", "heartRate", "glucose"]] # 因变量 y = data["TenYearCHD"] # 组成新的数据集 new_data = pd.concat([X, y], axis=1) # 打印新的数据集 print(new_data.head())

相关推荐

from sklearn.datasets import load_iris from sklearn. model_selection import train_test_split from sklearn.metrics import classification_report from sklearn. neighbors import KNeighborsClassifier from sklearn. metrics import roc_curve, auc import matplotlib.pyplot as plt from sklearn. metrics import confusion_matrix import seaborn as sns import scikitplot as skplt #加载数据集 iris = load_iris() data = iris['data'] label = iris['target'] #数据集的划分 x_train,x_test,y_train,y_test = train_test_split(data,label,test_size=0.3) print(x_train) #模型构建 model = KNeighborsClassifier(n_neighbors=5) model.fit(x_train,y_train) #模型评估 #(1)精确率,召回率,F1分数,准确率(宏平均和微平均) predict = model. predict(x_test) result = classification_report(y_test,predict) print(result) # (2) 混淆矩阵 confusion_matrix = confusion_matrix(y_test, predict) print('混淆矩阵:', confusion_matrix) sns.set(font_scale=1) sns.heatmap(confusion_matrix, annot=True, annot_kws={"size", 16}, cmap=plt.cm.Blues) plt.title('Confusion Matrix') plt.ylabel('True label' ) plt.xlabel('Predicted label') plt.savefig('Confusion matrix. pdf') plt.show() #(3)ROC曲线 Y_pred_prob = model. predict_proba(x_test) plt.figure(figsize= (7,7)) ax= plt. subplot() skplt.metrics.plot_roc_curve(y_test,Y_pred_prob,ax= ax) ax.set_xlabel('False Positive Rate', fontsize = 20) ax.set_ylabel('True Positive Rate ',fontsize = 20) ax.set_title('ROC Areas ',fontsize = 20) plt.xlim((0, 1)) plt.ylim((0, 1)) plt.xticks(fontsize = 18) plt.yticks(fontsize = 18) plt.legend(fontsize =18) plt.savefig(' ROC.pdf') plt.show( ) #(4)P_R曲线 from sklearn.metrics import precision_recall_curve precision, recall, _ =precision_recall_curve(y_test) plt.fill_between(recall, precision,color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.0]) plt.xlim([0.0, 1.0]) plt.plot(recall, precision) plt.title("Precision-Recall") plt.show()

import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, confusion_matrix,classification_report import seaborn as sns import matplotlib.pyplot as plt # 读取数据 data = pd.read_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测样本.xlsx') # 分割训练集和验证集 train_data = data.sample(frac=0.8, random_state=1) test_data = data.drop(train_data.index) # 定义特征变量和目标变量 features = ['高程', '起伏度', '桥梁长', '道路长', '平均坡度', '平均地温', 'T小于0', '相态'] target = '交通风险' # 训练随机森林模型 rf = RandomForestClassifier(n_estimators=100, random_state=1) rf.fit(train_data[features], train_data[target]) # 在验证集上进行预测并计算精度、召回率和F1值等指标 pred = rf.predict(test_data[features]) accuracy = accuracy_score(test_data[target], pred) confusion_mat = confusion_matrix(test_data[target], pred) classification_rep = classification_report(test_data[target], pred) print('Accuracy:', accuracy) print('Confusion matrix:') print(confusion_mat) print('Classification report:') print(classification_rep) # 输出混淆矩阵图片 sns.heatmap(confusion_mat, annot=True, cmap="Blues") plt.show() # 读取新数据文件并预测结果 new_data = pd.read_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测结果/交通风险预测096.xlsx') new_pred = rf.predict(new_data[features]) new_data['交通风险预测结果'] = new_pred new_data.to_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测结果/交通风险预测096结果.xlsx', index=False)修改代码使得显示决策树模型以及多分类的roc曲线和auc值

import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix, classification_report, accuracy_score # 1. 数据准备 train_data = pd.read_csv('train.csv') test_data = pd.read_csv('test_noLabel.csv') # 填充缺失值 train_data.fillna(train_data.mean(), inplace=True) test_data.fillna(test_data.mean(), inplace=True) # 2. 特征工程 X_train = train_data.drop(['Label', 'ID'], axis=1) y_train = train_data['Label'] X_test = test_data.drop('ID', axis=1) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) # 3. 模型建立 model = RandomForestClassifier(n_estimators=100, random_state=42) # 4. 模型训练 model.fit(X_train, y_train) # 5. 进行预测 y_pred = model.predict(X_test) # 6. 保存预测结果 df_result = pd.DataFrame({'ID': test_data['ID'], 'Label': y_pred}) df_result.to_csv('forecast_result.csv', index=False) # 7. 模型评估 y_train_pred = model.predict(X_train) print('训练集准确率:', accuracy_score(y_train, y_train_pred)) print('测试集准确率:', accuracy_score(y_test, y_pred)) print(classification_report(y_test, y_pred)) # 8. 绘制柱形图 feature_importances = pd.Series(model.feature_importances_, index=X_train.columns) feature_importances = feature_importances.sort_values(ascending=False) plt.figure(figsize=(10, 6)) sns.barplot(x=feature_importances, y=feature_importances.index) plt.xlabel('Feature Importance Score') plt.ylabel('Features') plt.title('Visualizing Important Features') plt.show() # 9. 对比类分析 train_data['Label'].value_counts().plot(kind='bar', color=['blue', 'red']) plt.title('Class Distribution') plt.xlabel('Class') plt.ylabel('Frequency') plt.show()

最新推荐

recommend-type

六首页数字藏品NFT交易网React NextJS网站模板 六首页数字藏品nft交易网反应NextJS网站模板

六首页数字藏品NFT交易网React NextJS网站模板 六首页数字藏品nft交易网反应NextJS网站模板
recommend-type

wireshark安装教程入门

wireshark安装教程入门
recommend-type

基于C++负数据库的隐私保护在线医疗诊断系统

【作品名称】:基于C++负数据库的隐私保护在线医疗诊断系统 【适用人群】:适用于希望学习不同技术领域的小白或进阶学习者。可作为毕设项目、课程设计、大作业、工程实训或初期项目立项。 【项目介绍】: 基于负数据库的隐私保护在线医疗诊断系统 NDBMedicalSystem 客户端及服务器端 本项目是在保护用户隐私的前提下,完成了对新冠肺炎、乳腺癌、眼疾等多种疾病的智能诊断。
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

2. 通过python绘制y=e-xsin(2πx)图像

可以使用matplotlib库来绘制这个函数的图像。以下是一段示例代码: ```python import numpy as np import matplotlib.pyplot as plt def func(x): return np.exp(-x) * np.sin(2 * np.pi * x) x = np.linspace(0, 5, 500) y = func(x) plt.plot(x, y) plt.xlabel('x') plt.ylabel('y') plt.title('y = e^{-x} sin(2πx)') plt.show() ``` 运行这段
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这