ax[0].plt.plot(first_layer_activation[0,:,0], cmap="viridis")

时间: 2023-03-31 10:04:38 浏览: 63
这是一个关于 Python 数据可视化的问题,我可以回答。这段代码是用来绘制第一层激活函数的可视化图像,其中 first_layer_activation 是一个三维张量,第一个维度是样本数,第二个维度是特征图的尺寸,第三个维度是特征图的通道数。plt.plot() 函数用来绘制第一个通道的特征图的可视化图像,cmap="viridis" 表示使用 viridis 颜色映射方案。
相关问题

def draw_stats(self, vals, vals1, vals2, vals3, vals4, vals5, vals6): self.ax1 = plt.subplot(self.gs[0, 0]) self.ax1.plot(vals) self.ax1.set_xlim(self.xlim) locs = self.ax1.get_xticks() locs[0] = self.xlim[0] locs[-1] = self.xlim[1] self.ax1.set_xticks(locs) self.ax1.use_sticky_edges = False self.ax1.set_title(f'Connected Clients Ratio') self.ax2 = plt.subplot(self.gs[1, 0]) self.ax2.plot(vals1) self.ax2.set_xlim(self.xlim) self.ax2.set_xticks(locs) self.ax2.yaxis.set_major_formatter(FuncFormatter(format_bps)) self.ax2.use_sticky_edges = False self.ax2.set_title('Total Bandwidth Usage') self.ax3 = plt.subplot(self.gs[2, 0]) self.ax3.plot(vals2) self.ax3.set_xlim(self.xlim) self.ax3.set_xticks(locs) self.ax3.use_sticky_edges = False self.ax3.set_title('Bandwidth Usage Ratio in Slices (Averaged)') self.ax4 = plt.subplot(self.gs[3, 0]) self.ax4.plot(vals3) self.ax4.set_xlim(self.xlim) self.ax4.set_xticks(locs) self.ax4.use_sticky_edges = False self.ax4.set_title('Client Count Ratio per Slice') self.ax5 = plt.subplot(self.gs[0, 1]) self.ax5.plot(vals4) self.ax5.set_xlim(self.xlim) self.ax5.set_xticks(locs) self.ax5.use_sticky_edges = False self.ax5.set_title('Coverage Ratio') self.ax6 = plt.subplot(self.gs[1, 1]) self.ax6.plot(vals5) self.ax6.set_xlim(self.xlim) self.ax6.set_xticks(locs) self.ax6.yaxis.set_major_formatter(FormatStrFormatter('%.3f')) self.ax6.use_sticky_edges = False self.ax6.set_title('Block ratio') self.ax7 = plt.subplot(self.gs[2, 1]) self.ax7.plot(vals6) self.ax7.set_xlim(self.xlim) self.ax7.set_xticks(locs) self.ax7.yaxis.set_major_formatter(FormatStrFormatter('%.3f')) self.ax7.use_sticky_edges = False self.ax7.set_title('Handover ratio')修改为一张张输出图片

好的,你可以将这段代码修改为: ```python def draw_stats(self, vals, vals1, vals2, vals3, vals4, vals5, vals6, save_path): fig, axs = plt.subplots(4, 2, figsize=(16, 16)) axs[0, 0].plot(vals) axs[0, 0].set_xlim(self.xlim) locs = axs[0, 0].get_xticks() locs[0] = self.xlim[0] locs[-1] = self.xlim[1] axs[0, 0].set_xticks(locs) axs[0, 0].use_sticky_edges = False axs[0, 0].set_title(f'Connected Clients Ratio') axs[1, 0].plot(vals1) axs[1, 0].set_xlim(self.xlim) axs[1, 0].set_xticks(locs) axs[1, 0].yaxis.set_major_formatter(FuncFormatter(format_bps)) axs[1, 0].use_sticky_edges = False axs[1, 0].set_title('Total Bandwidth Usage') axs[2, 0].plot(vals2) axs[2, 0].set_xlim(self.xlim) axs[2, 0].set_xticks(locs) axs[2, 0].use_sticky_edges = False axs[2, 0].set_title('Bandwidth Usage Ratio in Slices (Averaged)') axs[3, 0].plot(vals3) axs[3, 0].set_xlim(self.xlim) axs[3, 0].set_xticks(locs) axs[3, 0].use_sticky_edges = False axs[3, 0].set_title('Client Count Ratio per Slice') axs[0, 1].plot(vals4) axs[0, 1].set_xlim(self.xlim) axs[0, 1].set_xticks(locs) axs[0, 1].use_sticky_edges = False axs[0, 1].set_title('Coverage Ratio') axs[1, 1].plot(vals5) axs[1, 1].set_xlim(self.xlim) axs[1, 1].set_xticks(locs) axs[1, 1].yaxis.set_major_formatter(FormatStrFormatter('%.3f')) axs[1, 1].use_sticky_edges = False axs[1, 1].set_title('Block ratio') axs[2, 1].plot(vals6) axs[2, 1].set_xlim(self.xlim) axs[2, 1].set_xticks(locs) axs[2, 1].yaxis.set_major_formatter(FormatStrFormatter('%.3f')) axs[2, 1].use_sticky_edges = False axs[2, 1].set_title('Handover ratio') plt.tight_layout() plt.savefig(save_path) plt.show() ``` 这样就可以一张张输出图片了,你只需要传入一个保存路径参数 `save_path` 即可。

绘制训练集和测试集的真实值和预测值图像 train_predict_plot = np.empty_like(data_scaled) train_predict_plot[:, :] = np.nan train_predict_plot[time_steps:len(train_predict) + time_steps, :] = train_predict test_predict_plot = np.empty_like(data_scaled) test_predict_plot[:, :] = np.nan test_predict_plot[len(train_predict) + time_steps * 2 + 1:len(data_scaled) - 1, :] = test_predict plt.figure(figsize=(10, 6)) plt.plot(scaler.inverse_transform(data_scaled)) plt.plot(train_predict_plot) plt.plot(test_predict_plot) plt.legend(['True', 'Train Predict', 'Test Predict']) plt.xlabel('Time/h') plt.ylabel('kwh') plt.show(改写以上代码,使得训练集部分和测试集部分分别绘制在两张图上

下面是改写后的代码,将训练集和测试集的真实值和预测值分别绘制在两张图上: ``` train_predict_plot = np.empty_like(data_scaled) train_predict_plot[:, :] = np.nan train_predict_plot[time_steps:len(train_predict) + time_steps, :] = train_predict test_predict_plot = np.empty_like(data_scaled) test_predict_plot[:, :] = np.nan test_predict_plot[len(train_predict) + time_steps * 2 + 1:len(data_scaled) - 1, :] = test_predict # 绘制训练集部分真实值和预测值图像 plt.figure(figsize=(10, 6)) plt.plot(scaler.inverse_transform(data_scaled[:len(train_predict)])) plt.plot(train_predict_plot[:len(train_predict)]) plt.legend(['True', 'Train Predict']) plt.xlabel('Time/h') plt.ylabel('kwh') plt.title('Training Set') plt.show() # 绘制测试集部分真实值和预测值图像 plt.figure(figsize=(10, 6)) plt.plot(scaler.inverse_transform(data_scaled[len(train_predict) + time_steps * 2 + 1:])) plt.plot(test_predict_plot[len(train_predict) + time_steps * 2 + 1:]) plt.legend(['True', 'Test Predict']) plt.xlabel('Time/h') plt.ylabel('kwh') plt.title('Test Set') plt.show() ```

相关推荐

import pandas as pd import warnings import sklearn.datasets import sklearn.linear_model import matplotlib import matplotlib.font_manager as fm import matplotlib.pyplot as plt import numpy as np import seaborn as sns data = pd.read_excel(r'C:\Users\Lenovo\Desktop\data.xlsx') print(data.info()) fig = plt.figure(figsize=(10, 8)) sns.heatmap(data.corr(), cmap="YlGnBu", annot=True) plt.title('相关性分析热力图') plt.rcParams['axes.unicode_minus'] = False plt.rcParams['font.sans-serif'] = 'SimHei' plt.show() y = data['y'] x = data.drop(['y'], axis=1) print('************************输出新的特征集数据***************************') print(x.head()) from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42) def relu(x): output=np.maximum(0, x) return output def relu_back_propagation(derror_wrt_output,x): derror_wrt_dinputs = np.array(derror_wrt_output, copy=True) derror_wrt_dinputs[x <= 0] = 0 return derror_wrt_dinputs def activated(activation_choose,x): if activation_choose == 'relu': return relu(x) def activated_back_propagation(activation_choose, derror_wrt_output, output): if activation_choose == 'relu': return relu_back_propagation(derror_wrt_output, output) class NeuralNetwork: def __init__(self, layers_strcuture, print_cost = False): self.layers_strcuture = layers_strcuture self.layers_num = len(layers_strcuture) self.param_layers_num = self.layers_num - 1 self.learning_rate = 0.0618 self.num_iterations = 2000 self.x = None self.y = None self.w = dict() self.b = dict() self.costs = [] self.print_cost = print_cost self.init_w_and_b() def set_learning_rate(self,learning_rate): self.learning_rate=learning_rate def set_num_iterations(self, num_iterations): self.num_iterations = num_iterations def set_xy(self, input, expected_output): self.x = input self.y = expected_output

import numpy as np import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt ## Let us define a plt function for simplicity def plt_loss(x,training_metric,testing_metric,ax,colors = ['b']): ax.plot(x,training_metric,'b',label = 'Train') ax.plot(x,testing_metric,'k',label = 'Test') ax.set_xlabel('Epochs') ax.set_ylabel('Accuarcy')# ax.set_ylabel('Categorical Crossentropy Loss') plt.legend() plt.grid() plt.show() tf.keras.utils.set_random_seed(1) ## We import the Minist Dataset using Keras.datasets (train_data, train_labels), (test_data, test_labels) = keras.datasets.mnist.load_data() ## We first vectorize the image (28*28) into a vector (784) train_data = train_data.reshape(train_data.shape[0],train_data.shape[1]train_data.shape[2]) # 60000784 test_data = test_data.reshape(test_data.shape[0],test_data.shape[1]test_data.shape[2]) # 10000784 ## We next change label number to a 10 dimensional vector, e.g., 1->[0,1,0,0,0,0,0,0,0,0] train_labels = keras.utils.to_categorical(train_labels,10) test_labels = keras.utils.to_categorical(test_labels,10) ## start to build a MLP model N_batch_size = 5000 N_epochs = 100 lr = 0.01 ## we build a three layer model, 784 -> 64 -> 10 MLP_4 = keras.models.Sequential([ keras.layers.Dense(128, input_shape=(784,),activation='relu'), keras.layers.Dense(64,activation='relu'), keras.layers.Dense(10,activation='softmax') ]) MLP_4.compile( optimizer=keras.optimizers.Adam(lr), loss= 'categorical_crossentropy', metrics = ['accuracy'] ) History = MLP_4.fit(train_data[:10000],train_labels[:10000], batch_size = N_batch_size, epochs = N_epochs,validation_data=(test_data,test_labels), shuffle=False) train_acc = History.history['accuracy'] test_acc = History.history['val_accuracy']在该模型中加入early stopping,使用monitor='loss', patience = 2设置代码

import numpy as np import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt Let us define a plt function for simplicity def plt_loss(x,training_metric,testing_metric,ax,colors = ['b']): ax.plot(x,training_metric,'b',label = 'Train') ax.plot(x,testing_metric,'k',label = 'Test') ax.set_xlabel('Epochs') ax.set_ylabel('Accuracy') plt.legend() plt.grid() plt.show() tf.keras.utils.set_random_seed(1) We import the Minist Dataset using Keras.datasets (train_data, train_labels), (test_data, test_labels) = keras.datasets.mnist.load_data() We first vectorize the image (28*28) into a vector (784) train_data = train_data.reshape(train_data.shape[0],train_data.shape[1]train_data.shape[2]) # 60000784 test_data = test_data.reshape(test_data.shape[0],test_data.shape[1]test_data.shape[2]) # 10000784 We next change label number to a 10 dimensional vector, e.g., 1-> train_labels = keras.utils.to_categorical(train_labels,10) test_labels = keras.utils.to_categorical(test_labels,10) start to build a MLP model N_batch_size = 5000 N_epochs = 100 lr = 0.01 we build a three layer model, 784 -> 64 -> 10 MLP_3 = keras.models.Sequential([ keras.layers.Dense(128, input_shape=(784,),activation='relu'), keras.layers.Dense(64, activation='relu'), keras.layers.Dense(10,activation='softmax') ]) MLP_3.compile( optimizer=keras.optimizers.Adam(lr), loss= 'categorical_crossentropy', metrics = ['accuracy'] ) History = MLP_3.fit(train_data,train_labels, batch_size = N_batch_size, epochs = N_epochs,validation_data=(test_data,test_labels), shuffle=False) train_acc = History.history['accuracy'] test_acc = History.history对于该模型,使用不同数量的训练数据(5000,10000,15000,…,60000,公差=5000的等差数列),绘制训练集和测试集准确率(纵轴)关于训练数据大小(横轴)的曲线

最新推荐

recommend-type

matplotlib 曲线图 和 折线图 plt.plot()实例

主要介绍了matplotlib 曲线图 和 折线图 plt.plot()实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

年终工作总结汇报PPTqytp.pptx

年终工作总结汇报PPTqytp.pptx
recommend-type

setuptools-32.1.1-py2.py3-none-any.whl

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
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

解释minorization-maximization (MM) algorithm,并给出matlab代码编写的例子

Minorization-maximization (MM) algorithm是一种常用的优化算法,用于求解非凸问题或含有约束的优化问题。该算法的基本思想是通过构造一个凸下界函数来逼近原问题,然后通过求解凸下界函数的最优解来逼近原问题的最优解。具体步骤如下: 1. 初始化参数 $\theta_0$,设 $k=0$; 2. 构造一个凸下界函数 $Q(\theta|\theta_k)$,使其满足 $Q(\theta_k|\theta_k)=f(\theta_k)$; 3. 求解 $Q(\theta|\theta_k)$ 的最优值 $\theta_{k+1}=\arg\min_\theta Q(
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集群由多个称为代理的服务器组成,这