plt.legend(('real', 'predict'), loc='upper right', fontsize='15')

时间: 2023-10-01 12:07:10 浏览: 23
This line of code adds a legend to a plot with two lines, labeled 'real' and 'predict'. The legend is placed in the upper right corner and the font size is set to 15.
相关问题

y_test = y_test.reset_index(drop = True) y_predict2 = model_RF1.predict(x_test) plt.figure(figsize = (12,8)) plt.plot(y_predict2,color = 'b',label = 'predict',markersize=8) plt.plot(y_test,color = 'r',label = 'true',markersize=8) plt.xlabel('Test Sample',fontsize=30) plt.ylabel('y1',fontsize=30) plt.title('随机森林',fontsize=30) #坐标轴字体大小 plt.xticks(fontsize=25) plt.yticks(fontsize=25) plt.legend(fontsize=25,loc='upper right') # plt.savefig('GradientBoosting.png',dpi=300,bbox_inches = 'tight')

这段代码的作用是对训练好的随机森林模型进行测试,并将测试结果和真实值进行可视化比较。首先,使用`reset_index()`函数将`y_test`的索引重置为默认值,即0到n-1。接着,使用训练好的`model_RF1`模型对测试集`x_test`进行预测,将预测结果存储在`y_predict2`中。然后,使用`plt.plot()`函数将预测结果和真实值分别用蓝色和红色的线绘制在图表上。接下来,使用`plt.xlabel()`和`plt.ylabel()`函数分别设置x轴和y轴的标签,使用`plt.title()`函数设置图表的标题。然后,使用`plt.xticks()`和`plt.yticks()`函数设置x轴和y轴刻度标签的字体大小。最后,使用`plt.legend()`函数添加图例,并设置字体大小和位置。如果需要保存图表,可以使用`plt.savefig()`函数。

请你帮我优化这一串代码:have=pd.read_csv('1_1mean_2.csv',header=None) X=have.iloc[:, 0:-1] #y=have['血糖'].values.astype(int) y=have.iloc[:,-1] X_train,X_test,y_train,y_test=model_selection.train_test_split(X,y,test_size=0.8,random_state=1) #决策树 regressor = DecisionTreeRegressor.fit(X_train,y_train) #十折交叉验证模型的性能 print(cross_val_score(regressor, X, y, cv=10)) #预测 y_pred=regressor.predict(X_test) from sklearn import metrics test_err=metrics.mean_squared_error(y_test,y_pred) print("均方误差:",test_err) #metrics.confusion_matrix(y_test, y_pred) print("正确性:",regressor.score(X_test,y_test)) draw=pd.concat([pd.DataFrame(y_test),pd.DataFrame(y_pred)],axis=1); draw.iloc[-100:,0].plot(figsize=(12,6)) draw.iloc[-100:,1].plot(figsize=(12,6)) plt.legend(('real', 'predict'),loc='upper right',fontsize='15') plt.title("Test Data",fontsize='30') #添加标题 plt.show()

优化后的代码如下: ```python import pandas as pd from sklearn.tree import DecisionTreeRegressor from sklearn import model_selection, metrics import matplotlib.pyplot as plt # 读取数据 have = pd.read_csv('1_1mean_2.csv', header=None) # 划分特征和标签 X = have.iloc[:, 0:-1] y = have.iloc[:, -1] # 划分训练集和测试集 X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size=0.8, random_state=1) # 训练决策树模型 regressor = DecisionTreeRegressor() regressor.fit(X_train, y_train) # 十折交叉验证模型的性能 scores = model_selection.cross_val_score(regressor, X, y, cv=10) print(scores) # 预测 y_pred = regressor.predict(X_test) # 计算均方误差 test_err = metrics.mean_squared_error(y_test, y_pred) print("均方误差:", test_err) # 输出正确性 print("正确性:", regressor.score(X_test, y_test)) # 绘制预测结果和真实结果对比图 draw = pd.concat([y_test.reset_index(drop=True), pd.Series(y_pred)], axis=1) draw.iloc[-100:, 0].plot(figsize=(12, 6)) draw.iloc[-100:, 1].plot(figsize=(12, 6)) plt.legend(('real', 'predict'), loc='upper right', fontsize='15') plt.title("Test Data", fontsize='30') plt.show() ``` 优化说明: - 将导入的模块放在代码开头,提高代码可读性。 - 将决策树模型的训练过程分离出来,提高代码结构清晰度。 - 使用更加具有描述性的变量名。 - 使用`reset_index`方法对索引进行重置,确保绘图时索引对齐。 - 修正`DecisionTreeRegressor`的实例化方式。 - 添加注释,提高代码可维护性。

相关推荐

depth = np.arange(1, 15) err_train_list = [] err_test_list = [] clf = DecisionTreeClassifier(criterion='entropy') for d in depth: clf.set_params(max_depth=d) clf.fit(x_train, y_train) y_train_pred = clf.predict(x_train) err_train = 1-accuracy_score(y_train, y_train_pred) err_train_list.append(err_train) y_test_pred = clf.predict(x_test) err_test = 1-accuracy_score(y_test, y_test_pred) err_test_list.append(err_test) print(d, '测试集错误率:%.2f%%' % (100 * err_test)) plt.figure(facecolor='w') plt.plot(depth, err_test_list, 'ro-', markeredgecolor='k', lw=2, label='测试集错误率') plt.plot(depth, err_train_list, 'go-', markeredgecolor='k', lw=2, label='训练集错误率') plt.xlabel('决策树深度', fontsize=13) plt.ylabel('错误率', fontsize=13) plt.legend(loc='lower left', fontsize=13) plt.title('决策树深度与过拟合', fontsize=15) plt.grid(b=True, ls=':', color='#606060') depth = np.arange(1, 15) err_train_list = [] err_test_list = [] clf = DecisionTreeClassifier(criterion='entropy') for d in depth: clf.set_params(max_depth=d) clf.fit(x_train, y_train) y_train_pred = clf.predict(x_train) err_train = 1-accuracy_score(y_train, y_train_pred) err_train_list.append(err_train) y_test_pred = clf.predict(x_test) err_test = 1-accuracy_score(y_test, y_test_pred) err_test_list.append(err_test) print(d, '测试集错误率:%.2f%%' % (100 * err_test)) plt.figure(facecolor='w') plt.plot(depth, err_test_list, 'ro-', markeredgecolor='k', lw=2, label='测试集错误率') plt.plot(depth, err_train_list, 'go-', markeredgecolor='k', lw=2, label='训练集错误率') plt.xlabel('决策树深度', fontsize=13) plt.ylabel('错误率', fontsize=13) plt.legend(loc='lower left', fontsize=13) plt.title('决策树深度与过拟合', fontsize=15) plt.grid(b=True, ls=':', color='#606060') plt.show()

def show_ROC(): global X_train,X_test,y_train,y_test model = RandomForestClassifier(max_depth=20, random_state=1234) model.fit(X_train, y_train) score_window = tk.Toplevel(window) score_window.geometry("600x600") score_window.title("随机森林-ROC") y_prod = model.predict_proba(X_test)[:, 1] false_positive_rate, true_positive_rate, thresholds = roc_curve(y_test, y_prod) roc = auc(false_positive_rate, true_positive_rate) # 创建一个新的Figure对象 fig = plt.figure(figsize=(10, 10)) plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False plt.plot(false_positive_rate, true_positive_rate, color='red', label='AUC = %0.2f' % roc) plt.legend(loc='lower right') plt.plot([0, 1], [0, 1], linestyle='--') plt.axis('tight') plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.title('ROC') # 添加ROC曲线的通俗解释 roc_explanation = "ROC曲线反映了不同阈值下模型的分类能力,AUC值越高代表模型效果越好。ROC曲线通过计算不同阈值下的真正率和假正率,形成一条曲线来反映模型的分类能力。如果ROC曲线越靠近左上角,则代表模型的性能越好。" plt.text(0.5, -0.1, roc_explanation, ha='center', va='center', fontsize=10, transform=plt.gca().transAxes) # 将Figure对象添加到Canvas对象中,并将Canvas对象添加到tkinter窗口中 canvas = FigureCanvasTkAgg(fig, master=score_window) canvas.draw() canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)

data = pd.read_csv("data.csv") data.replace("M",1,inplace=True) data.replace("B",0,inplace=True) #获取特征x和特征y X = data.iloc[:, 3:5].values x = np.array(X) y = data.diagnosis y = np.array(y) #创建决策树算法对象 tree_clf = DecisionTreeClassifier(max_depth=2) #构建决策树 tree_clf.fit(x,y) #绘制决策树结构 tree.plot_tree(tree_clf) from matplotlib.colors import ListedColormap plt.rcParams["font.sans-serif"] = ["SimHei"] plt.rcParams["axes.unicode_minus"] = False #定义绘制决策树边界的函数 def plot_decision_boundary(clf, X, y, axes=[0, 10 , 0 , 5], data=True, legend=False, plot_training=True): x1s = np.linspace(axes[0], axes[1], 100) x2s = np.linspace(axes[2], axes[3], 100) x1, x2 = np.meshgrid(x1s, x2s) X_new = np.c_[x1.ravel(), x2.ravel()] y_pred = clf.predict(X_new).reshape(x1.shape) custom_cmap = ListedColormap(['#fafab0', '#0909ff', '#a0faa0']) plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap) if not data: custom_cmap2 = ListedColormap(['#7d7d58', '#4c4c7f', '#507d50']) plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8) if plot_training: plt.plot(X[:, 0][y == 0], X[:, 1][y == 0], "yo", label="0") plt.plot(X[:, 0][y == 1], X[:, 1][y == 1],"bs", label="1") plt.axis(axes) if data: plt.xlabel("属性",fontsize=14) plt.ylabel("特征",fontsize=14) else: plt.xlabel(r"$x_1$", fontsize=18) plt.xlabel(r"$x_2$", fontsize=18,rotation=0) if legend: plt.legend(loc="lower right", fontsize=14) tree_clf1 = DecisionTreeClassifier(random_state=42) tree_clf2 = DecisionTreeClassifier(min_samples_leaf=4,random_state=43) tree_clf1.fit(x,y) tree_clf2.fit(x,y) plt.figure(figsize=(15,6)) plt.subplot(121) plot_decision_boundary(tree_clf1, x, y, axes=[0, 40, 50, 150], data=False) plt.title('圖一') plt.subplot(122) plot_decision_boundary(tree_clf2, x, y, axes=[0, 40, 50, 150], data=False) plt.title('圖二')

import numpy as np import pandas as pd import matplotlib.pyplot as plt import BPNN from sklearn import metrics from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error #导入必要的库 df1=pd.read_excel(r'D:\Users\Desktop\大数据\44.xls',0) df1=df1.iloc[:,:] #进行数据归一化 from sklearn import preprocessing min_max_scaler = preprocessing.MinMaxScaler() df0=min_max_scaler.fit_transform(df1) df = pd.DataFrame(df0, columns=df1.columns) x=df.iloc[:,:4] y=df.iloc[:,-1] #划分训练集测试集 cut=4#取最后cut=30天为测试集 x_train, x_test=x.iloc[4:],x.iloc[:4]#列表的切片操作,X.iloc[0:2400,0:7]即为1-2400行,1-7列 y_train, y_test=y.iloc[4:],y.iloc[:4] x_train, x_test=x_train.values, x_test.values y_train, y_test=y_train.values, y_test.values #神经网络搭建 bp1 = BPNN.BPNNRegression([4, 16, 1]) train_data=[[sx.reshape(4,1),sy.reshape(1,1)] for sx,sy in zip(x_train,y_train)] test_data = [np.reshape(sx,(4,1))for sx in x_test] #神经网络训练 bp1.MSGD(train_data, 1000, len(train_data), 0.2) #神经网络预测 y_predict=bp1.predict(test_data) y_pre = np.array(y_predict) # 列表转数组 y_pre=y_pre.reshape(4,1) y_pre=y_pre[:,0] #画图 #展示在测试集上的表现 draw=pd.concat([pd.DataFrame(y_test),pd.DataFrame(y_pre)],axis=1); draw.iloc[:,0].plot(figsize=(12,6)) draw.iloc[:,1].plot(figsize=(12,6)) plt.legend(('real', 'predict'),loc='upper right',fontsize='15') plt.title("Test Data",fontsize='30') #添加标题 #输出精度指标 print('测试集上的MAE/MSE') print(mean_absolute_error(y_pre, y_test)) print(mean_squared_error(y_pre, y_test) ) mape = np.mean(np.abs((y_pre-y_test)/(y_test)))*100 print('=============mape==============') print(mape,'%') # 画出真实数据和预测数据的对比曲线图 print("R2 = ",metrics.r2_score(y_test, y_pre)) # R2 运行上述程序。在下面这一步中draw=pd.concat([pd.DataFrame(y_test),pd.DataFrame(y_pre)],axis=1);我需要将归一化的数据变成真实值,输出对比图,该怎么修改程序

#importing required libraries from sklearn.preprocessing import MinMaxScaler from keras.models import Sequential from keras.layers import Dense, Dropout, LSTM #setting index data = df.sort_index(ascending=True, axis=0) new_data = data[['trade_date', 'close']] new_data.index = new_data['trade_date'] new_data.drop('trade_date', axis=1, inplace=True) new_data.head() #creating train and test sets dataset = new_data.values train= dataset[0:1825,:] valid = dataset[1825:,:] #converting dataset into x_train and y_train scaler = MinMaxScaler(feature_range=(0, 1)) scaled_data = scaler.fit_transform(dataset) x_train, y_train = [], [] for i in range(60,len(train)): x_train.append(scaled_data[i-60:i,0]) y_train.append(scaled_data[i,0]) x_train, y_train = np.array(x_train), np.array(y_train) x_train = np.reshape(x_train, (x_train.shape[0],x_train.shape[1],1)) # create and fit the LSTM network model = Sequential() model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1],1))) model.add(LSTM(units=50)) model.add(Dense(1)) model.compile(loss='mean_squared_error', optimizer='adam') model.fit(x_train, y_train, epochs=1, batch_size=1, verbose=1) #predicting 246 values, using past 60 from the train data inputs = new_data[len(new_data) - len(valid) - 60:].values inputs = inputs.reshape(-1,1) inputs = scaler.transform(inputs) X_test = [] for i in range(60,inputs.shape[0]): X_test.append(inputs[i-60:i,0]) X_test = np.array(X_test) X_test = np.reshape(X_test, (X_test.shape[0],X_test.shape[1],1)) closing_price = model.predict(X_test) closing_price1 = scaler.inverse_transform(closing_price) rms=np.sqrt(np.mean(np.power((valid-closing_price1),2))) rms #v=new_data[1825:] valid1 = pd.DataFrame() # 假设你使用的是Pandas DataFrame valid1['Pre_Lstm'] = closing_price1 train=new_data[:1825] plt.figure(figsize=(16,8)) plt.plot(train['close']) plt.plot(valid1['close'],label='真实值') plt.plot(valid1['Pre_Lstm'],label='预测值') plt.title('LSTM预测',fontsize=16) plt.xlabel('日期',fontsize=14) plt.ylabel('收盘价',fontsize=14) plt.legend(loc=0)

最新推荐

recommend-type

山东省PLC与控制技术模拟试题.docx

plc
recommend-type

Мартин -- Байесовский анализ на Python -- 2020.pdf

Мартин -- Байесовский анализ на Python -- 2020
recommend-type

2022-2028全球与中国X射线探测器市场现状及未来发展趋势.docx

2022-2028全球与中国X射线探测器市场现状及未来发展趋势.docx
recommend-type

安卓版的c语言编译器IDE输出内容到文本文件代码正确例题.txt

安卓版的c语言编译器IDE输出内容到文本文件代码正确例题
recommend-type

霹雳六号进销存及应收付账会计系统 2024版

霹雳进销存是台湾知名通用性极强企业进销存管理系统,软件囊括了企业进、销、存管理的全过程,软件操作界面友好、灵活、易操作。 霹雳六号2024 进销存+会计 专业版 无30天100笔限制 付费授权安装密码 WFR77DQJJBPXMXV 安装完成后登入 使用者名称 pili 用户密码 pili
recommend-type

电力电子系统建模与控制入门

"该资源是关于电力电子系统建模及控制的课程介绍,包含了课程的基本信息、教材与参考书目,以及课程的主要内容和学习要求。" 电力电子系统建模及控制是电力工程领域的一个重要分支,涉及到多学科的交叉应用,如功率变换技术、电工电子技术和自动控制理论。这门课程主要讲解电力电子系统的动态模型建立方法和控制系统设计,旨在培养学生的建模和控制能力。 课程安排在每周二的第1、2节课,上课地点位于东12教401室。教材采用了徐德鸿编著的《电力电子系统建模及控制》,同时推荐了几本参考书,包括朱桂萍的《电力电子电路的计算机仿真》、Jai P. Agrawal的《Powerelectronicsystems theory and design》以及Robert W. Erickson的《Fundamentals of Power Electronics》。 课程内容涵盖了从绪论到具体电力电子变换器的建模与控制,如DC/DC变换器的动态建模、电流断续模式下的建模、电流峰值控制,以及反馈控制设计。还包括三相功率变换器的动态模型、空间矢量调制技术、逆变器的建模与控制,以及DC/DC和逆变器并联系统的动态模型和均流控制。学习这门课程的学生被要求事先预习,并尝试对书本内容进行仿真模拟,以加深理解。 电力电子技术在20世纪的众多科技成果中扮演了关键角色,广泛应用于各个领域,如电气化、汽车、通信、国防等。课程通过列举各种电力电子装置的应用实例,如直流开关电源、逆变电源、静止无功补偿装置等,强调了其在有功电源、无功电源和传动装置中的重要地位,进一步凸显了电力电子系统建模与控制技术的实用性。 学习这门课程,学生将深入理解电力电子系统的内部工作机制,掌握动态模型建立的方法,以及如何设计有效的控制系统,为实际工程应用打下坚实基础。通过仿真练习,学生可以增强解决实际问题的能力,从而在未来的工程实践中更好地应用电力电子技术。
recommend-type

管理建模和仿真的文件

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

图像写入的陷阱:imwrite函数的潜在风险和规避策略,规避图像写入风险,保障数据安全

![图像写入的陷阱:imwrite函数的潜在风险和规避策略,规避图像写入风险,保障数据安全](https://static-aliyun-doc.oss-accelerate.aliyuncs.com/assets/img/zh-CN/2275688951/p86862.png) # 1. 图像写入的基本原理与陷阱 图像写入是计算机视觉和图像处理中一项基本操作,它将图像数据从内存保存到文件中。图像写入过程涉及将图像数据转换为特定文件格式,并将其写入磁盘。 在图像写入过程中,存在一些潜在陷阱,可能会导致写入失败或图像质量下降。这些陷阱包括: - **数据类型不匹配:**图像数据可能与目标文
recommend-type

protobuf-5.27.2 交叉编译

protobuf(Protocol Buffers)是一个由Google开发的轻量级、高效的序列化数据格式,用于在各种语言之间传输结构化的数据。版本5.27.2是一个较新的稳定版本,支持跨平台编译,使得可以在不同的架构和操作系统上构建和使用protobuf库。 交叉编译是指在一个平台上(通常为开发机)编译生成目标平台的可执行文件或库。对于protobuf的交叉编译,通常需要按照以下步骤操作: 1. 安装必要的工具:在源码目录下,你需要安装适合你的目标平台的C++编译器和相关工具链。 2. 配置Makefile或CMakeLists.txt:在protobuf的源码目录中,通常有一个CMa
recommend-type

SQL数据库基础入门:发展历程与关键概念

本文档深入介绍了SQL数据库的基础知识,首先从数据库的定义出发,强调其作为数据管理工具的重要性,减轻了开发人员的数据处理负担。数据库的核心概念是"万物皆关系",即使在面向对象编程中也有明显区分。文档讲述了数据库的发展历程,从早期的层次化和网状数据库到关系型数据库的兴起,如Oracle的里程碑式论文和拉里·埃里森推动的关系数据库商业化。Oracle的成功带动了全球范围内的数据库竞争,最终催生了SQL这一通用的数据库操作语言,统一了标准,使得关系型数据库成为主流。 接着,文档详细解释了数据库系统的构成,包括数据库本身(存储相关数据的集合)、数据库管理系统(DBMS,负责数据管理和操作的软件),以及数据库管理员(DBA,负责维护和管理整个系统)和用户应用程序(如Microsoft的SSMS)。这些组成部分协同工作,确保数据的有效管理和高效处理。 数据库系统的基本要求包括数据的独立性,即数据和程序的解耦,有助于快速开发和降低成本;减少冗余数据,提高数据共享性,以提高效率;以及系统的稳定性和安全性。学习SQL时,要注意不同数据库软件可能存在的差异,但核心语言SQL的学习是通用的,后续再根据具体产品学习特异性。 本文档提供了一个全面的框架,涵盖了SQL数据库从基础概念、发展历程、系统架构到基本要求的方方面面,对于初学者和数据库管理员来说是一份宝贵的参考资料。