用pytorch搭建简单CNN前馈网络处理三通道彩色图像

本文档介绍了如何使用PyTorch构建简单的CNN前馈网络来处理三通道彩色图像。首先,展示了如何自定义4x4的三个卷积核,并配合ReLU激活和池化操作。接着,对比了使用torch默认初始化卷积核的情况,由于每次卷积核的随机初始化,图像处理结果会有所不同。最后,添加了全连接层,但未包含softmax层,注意在连接全连接层前需进行数据展平。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近想重新学习简单CNN网络前向传播的搭建,发现网上好像没有用pytorch对三通道彩色图像进行处理的。

1.自定义初始化4*4的三个卷积核,然后经过各一次的relu激活和池化,pytorch中,处理图片必须一个batch一个batch的操作,所以我们要准备的数据的格式是 [batch_size, n_channels, hight, width],记录一下代码:

import cv2
import matplotlib.pyplot as plt


img_path = '1.jpg'

bgr_img = cv2.imread(img_path)

# bgr_img = bgr_img.transpose(2,0,1)
print(bgr_img.shape)
b,g,r = cv2.split(bgr_img)
img_rgb = cv2.merge([r,g,b])
gray_img = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
img_rgb1 = img_rgb.transpose(2,0,1)#将通道数放在最前面的位置
print(img_rgb.shape)


plt.figure()
plt.imshow(gray_img)
print(gray_img.shape)
# Normalise
gray_img = gray_img.astype("float32")/255
# print(gray_img.shape)
plt.figure()
plt.imshow(gray_img)
plt.figure()
plt.imshow(img_rgb)

# plt.show()

import numpy as np

filter_vals = np.array([[-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1], [-1, -1, 1, 1]],dtype=np.float64)
filter_vals=filter_vals
print('Filter shape: ', filter_vals.shape)
filter_1 = filter_vals
filter_2 = -filter_1
filter_3 = filter_1.T
# filter_4 = -filter_3
filters = np.array([filter_1, filter_2, filter_3])#, filter_4])
import torch
import torch.nn as nn
import torch.nn.functional as F


class Net(nn.Module):

    def __init__(self,weight):
        super(Net, self).__init__()
        # initializes the weights of the convolutional layer to be the weights of the 4 defined filters
        # k_height, k_width = weight.shape[2:]
        # assumes there are 4 grayscale filters
        self.conv = nn.Conv2d(111,111,4, bias=False)
        self.conv.weight = torch.nn.Parameter(weight)
        # define a pooling layer
        self.pool = nn.MaxPool2d(2, 2)

    def forward(self, x):
        # calculates the output of a convolutional layer
        # pre- and post-activation
        conv_x = self.conv(x)
        activated_x = F.relu(conv_x)
        print('activated_x-shape',activated_x.shape)
        # applies pooling layer
        pooled_x = self.pool(activated_x)

        # returns all layers
        return conv_x, activated_x, pooled_x


# instantiate the model and set the weights
weight = torch.from_numpy(filters).unsqueeze(0)#.type(torch.FloatTensor)
print("weight shape",weight.shape)
model = Net(weight)

# print out the layer in the network
print(model)


def viz_layer(layer, n_filters=1):
    fig = plt.figure(figsize=(20, 20))
    for i in range(n_filters):
        ax = fig.add_subplot(1, n_filters, i + 1)
        ax.imshow(np.squeeze(layer[0, i].data.numpy()))
        ax.set_title('Output %s' % str(i + 1))


# plt.imshow(gray_img, cmap='gray')

fig = plt.figure(figsize=(12, 6))
fig.subplots_adjust(left=0, right=1.5, bottom=0.8, top=1, hspace=0.05, wspace=0.05)
for i in range(3):
    ax = fig.add_subplot
### 卷积神经网络 (CNN) 的代码实现与解析 #### 使用 PyTorch 实现 CNN 模型 卷积神经网络(Convolutional Neural Network,CNN)是一种前馈神经网络,具有卷积层、池化层和全连接层三种主要结构[^1]。下面是一个简单CNN 模型在 PyTorch 中的实现: ```python import torch.nn as nn import torch.nn.functional as F class SimpleCNN(nn.Module): def __init__(self): super(SimpleCNN, self).__init__() # 定义卷积层 self.conv1 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=5) self.conv2 = nn.Conv2d(in_channels=6, out_channels=12, kernel_size=5) # 定义全连接层 self.fc1 = nn.Linear(in_features=12 * 4 * 4, out_features=120) self.fc2 = nn.Linear(in_features=120, out_features=60) self.out = nn.Linear(in_features=60, out_features=10) def forward(self, t): # 输入通过第一个卷积层并应用激活函数 ReLU 和最大池化操作 t = t.unsqueeze(1) # 增加通道维度 t = F.relu(self.conv1(t)) t = F.max_pool2d(t, kernel_size=2, stride=2) # 同样处理第二个卷积层 t = F.relu(self.conv2(t)) t = F.max_pool2d(t, kernel_size=2, stride=2) # 将张量展平以便送入全连接层 t = t.reshape(-1, 12 * 4 * 4) t = F.relu(self.fc1(t)) t = F.relu(self.fc2(t)) # 输出层不使用激活函数 t = self.out(t) return t ``` 此模型包含了两个卷积层 `conv1` 和 `conv2` ,以及三个全连接层 `fc1`, `fc2` 及最终输出层 `out`. 这些组件共同构成了一个基本但完整的 CNN 架构。 #### MATLAB 实现一维数据的 CNN 网络 对于一维信号的数据集,在MATLAB中可以构建如下所示的一维 CNN处理单或多输入/输出的情况: ```matlab layers = [ imageInputLayer([height width channels]) % 输入图像尺寸 convolution2dLayer(filterSize,numFilters,'Padding','same') % 第一层卷积 batchNormalizationLayer() % 批标准化 reluLayer() % ReLU 激活函数 maxPooling2dLayer(poolingSize,'Stride',stride) % 最大池化 fullyConnectedLayer(numHiddenUnits) % 全连接隐藏层 softmaxLayer() % Softmax 层用于分类任务 classificationLayer()] % 分类输出层 ``` 这里定义了一个包含卷积、批规范化、ReLU 非线性变换、最大池化的典型 CNN 结构,并以全连接层结束来完成特征映射到类别标签的任务转换过程[^3].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值