fig, ax = plt.subplots(1, 2) ax[0].imshow(x_data[12].squeeze(), cmap='gray') ax[1].imshow(y_data[12].squeeze(), cmap='gray')
时间: 2024-01-17 14:02:56 浏览: 108
这是一个使用 Matplotlib 库绘制图像的代码片段。该代码创建了一个包含两个子图的图形窗口,第一个子图显示 x_data 列表中索引为 12 的图像,第二个子图显示 y_data 列表中索引为 12 的图像。其中,squeeze() 函数用于删除数组的单维度条目,cmap 参数用于指定色彩图的颜色映射。
相关问题
def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')): """ x: Features to be visualized module_type: Module type stage: Module stage within model n: Maximum number of feature maps to plot save_dir: Directory to save results """ if 'Detect' not in module_type: batch, channels, height, width = x.shape # batch, channels, height, width if height > 1 and width > 1: f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels n = min(n, channels) # number of plots fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols ax = ax.ravel() plt.subplots_adjust(wspace=0.05, hspace=0.05) for i in range(n): ax[i].imshow(blocks[i].squeeze()) # cmap='gray' ax[i].axis('off') LOGGER.info(f'Saving {f}... ({n}/{channels})') plt.savefig(f, dpi=300, bbox_inches='tight') plt.close() np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy()) # npy save
这段代码是用于可视化特征图的函数。它接受参数x(要可视化的特征)、module_type(模块类型)、stage(模型中的模块阶段)、n(要绘制的最大特征图数量)和save_dir(保存结果的目录)。
函数首先检查module_type中是否包含"Detect",如果不包含,则假设x的形状为(batch, channels, height, width)。然后根据height和width的值确定特征图是否是二维的。
接下来,函数将特征图拆分为多个块,每个块对应一个通道。然后,它创建一个子图网格,将每个特征图块绘制在其中,并保存结果。
最后,函数使用numpy保存特征图的数组,并返回保存的文件路径。
请注意,该代码依赖于torch、matplotlib和numpy等库。你需要确保这些库已经安装在你的环境中才能运行该代码。
import numpy as np import matplotlib.pyplot as plt from scipy import signal t = np.linspace(0, 2 * np.pi, 128, endpoint=False) x = np.sin(2 * t) print(x) kernel1 = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel2 = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]]) result1 = signal.convolve2d(x.reshape(1, -1), kernel1, mode='same') result2 = signal.convolve2d(x.reshape(1, -1), kernel2, mode='same') fig, axs = plt.subplots(3, 1, figsize=(8, 8)) axs[0].plot(t, x) axs[0].set_title('Original signal') axs[1].imshow(kernel1) axs[1].set_title('Kernel 1') axs[2].imshow(kernel2) axs[2].set_title('Kernel 2') fig.tight_layout() fig, axs = plt.subplots(3, 1, figsize=(8, 8)) axs[0].plot(t, x) axs[0].set_title('Original signal') axs[1].plot(t, result1.flatten()) axs[1].set_title('Result of convolution with kernel 1') axs[2].plot(t, result2.flatten()) axs[2].set_title('Result of convolution with kernel 2') fig.tight_layout() plt.show() # from scipy.signal import pool import numpy as np def pool(signal, window_size, mode='max'): if mode == 'max': return np.max(signal.reshape(-1, window_size), axis=1) elif mode == 'min': return np.min(signal.reshape(-1, window_size), axis=1) elif mode == 'mean': return np.mean(signal.reshape(-1, window_size), axis=1) else: raise ValueError("Invalid mode. Please choose 'max', 'min', or 'mean'.") # 对卷积结果进行最大池化 pool_size = 2 result1_pooled = pool(result1, pool_size, 'max') result2_pooled = pool(result2, pool_size, 'max') # 可视化结果 fig, axs = plt.subplots(3, 1, figsize=(8, 8)) axs[0].plot(t, x) axs[0].set_title('Original signal') axs[1].plot(t, result1.flatten()) axs[1].set_title('Result of convolution with kernel 1') axs[2].plot(t[::2], result1_pooled.flatten()) axs[2].set_title('Result of max pooling after convolution with kernel 1') fig.tight_layout() plt.show()给这段代码添加全连接层,每一步公式结果都要出结果图
好的,我来添加全连接层。这里我使用 Keras API 来添加神经网络层,代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv1D, MaxPooling1D, Flatten, Dense
t = np.linspace(0, 2 * np.pi, 128, endpoint=False)
x = np.sin(2 * t)
kernel1 = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]])
kernel2 = np.array([[1, 2, 1], [0, 0, 0], [-1, -2, -1]])
result1 = signal.convolve2d(x.reshape(1, -1), kernel1, mode='same')
result2 = signal.convolve2d(x.reshape(1, -1), kernel2, mode='same')
# 创建一个 Sequential 模型
model = Sequential()
# 添加一个 Conv1D 层,设置输入形状为 (input_length, input_dim) ,使用 32 个 3x3 的卷积核,使用 relu 激活函数
model.add(Conv1D(32, 3, activation='relu', input_shape=(128, 1)))
# 添加一个 MaxPooling1D 层,池化窗口大小为 2
model.add(MaxPooling1D(2))
# 添加一个 Flatten 层
model.add(Flatten())
# 添加一个 Dense 层,输出维度为 64 ,使用 relu 激活函数
model.add(Dense(64, activation='relu'))
# 添加一个 Dense 层,输出维度为 1 ,不使用激活函数
model.add(Dense(1))
# 编译模型
model.compile(loss='mse', optimizer='adam')
# 将输入信号转换为形状为 (1, 128, 1) 的数组
x = x.reshape(1, 128, 1)
# 训练模型
model.fit(x, result1.T, epochs=50, verbose=0)
# 对卷积结果进行最大池化
pool_size = 2
result1_pooled = signal.convolve2d(pool(result1, pool_size, 'max').reshape(1, -1), np.ones((1, pool_size)), mode='valid')
# 在模型中进行预测
result1_pred = model.predict(x).T
# 可视化结果
fig, axs = plt.subplots(3, 2, figsize=(8, 12))
axs[0, 0].plot(t, x.squeeze())
axs[0, 0].set_title('Original signal')
axs[1, 0].imshow(kernel1)
axs[1, 0].set_title('Kernel 1')
axs[2, 0].imshow(kernel2)
axs[2, 0].set_title('Kernel 2')
axs[0, 1].plot(t, result1.flatten())
axs[0, 1].set_title('Result of convolution with kernel 1')
axs[1, 1].plot(t, result1_pooled.flatten())
axs[1, 1].set_title('Result of max pooling after convolution with kernel 1')
axs[2, 1].plot(t, result1_pred.flatten())
axs[2, 1].set_title('Result of neural network after convolution with kernel 1')
fig.tight_layout()
plt.show()
```
在这里,我添加了一个包含一个卷积层、一个池化层、一个全连接层和一个输出层的神经网络。输入信号被转换为形状为 (1, 128, 1) 的数组,并传递给模型进行训练。最后,我在模型中进行预测,然后将结果可视化。注意,因为模型的输出维度为 1,所以我在可视化结果时使用了 `result1_pred.flatten()` 来展平结果。
阅读全文
相关推荐















