【卷积神经网络】例题XO - Python实现 - PyTorch版本
题目及理论讲解:
【卷积神经网络】例题XO - Python实现 - HBU_DAVID - 博客园 (cnblogs.com)
PyTorch实现代码:
# https://blog.csdn.net/qq_26369907/article/details/88366147 # https://zhuanlan.zhihu.com/p/405242579 import numpy as np import torch import torch.nn as nn x = torch.tensor([[[[-1, -1, -1, -1, -1, -1, -1, -1, -1], [-1, 1, -1, -1, -1, -1, -1, 1, -1], [-1, -1, 1, -1, -1, -1, 1, -1, -1], [-1, -1, -1, 1, -1, 1, -1, -1, -1], [-1, -1, -1, -1, 1, -1, -1, -1, -1], [-1, -1, -1, 1, -1, 1, -1, -1, -1], [-1, -1, 1, -1, -1, -1, 1, -1, -1], [-1, 1, -1, -1, -1, -1, -1, 1, -1], [-1, -1, -1, -1, -1, -1, -1, -1, -1]]]], dtype=torch.float) print(x.shape) print(x) print(--------------- 卷积 ---------------) conv1 = nn.Conv2d(1, 1, (3, 3), 1) # in_channel , out_channel , kennel_size , stride conv1.weight.data = torch.Tensor([[[[1, -1, -1], [-1, 1, -1], [-1, -1, 1]] ]]) conv2 = nn.Conv2d(1, 1, (3, 3), 1) # in_channel , out_channel , kennel_size , stride conv2.weight.data = torch.Tensor([[[[1, -1, 1], [-1, 1, -1], [1, -1, 1]] ]]) conv3 = nn.Conv2d(1, 1, (3, 3), 1) # in_channel , out_channel , kennel_size , stride conv3.weight.data = torch.Tensor([[[[-1, -1, 1], [-1, 1, -1], [1, -1, -1]] ]]) feature_map1 = conv1(x) feature_map2 = conv2(x) feature_map3 = conv3(x) print(feature_map1 / 9) print(feature_map2 / 9) print(feature_map3 / 9) print(--------------- 池化 ---------------) max_pool = nn.MaxPool2d(2, padding=0, stride=2) # Pooling zeroPad = nn.ZeroPad2d(padding=(0, 1, 0, 1)) # pad 0 , Left Right Up Down feature_map_pad_0_1 = zeroPad(feature_map1) feature_pool_1 = max_pool(feature_map_pad_0_1) feature_map_pad_0_2 = zeroPad(feature_map2) feature_pool_2 = max_pool(feature_map_pad_0_2) feature_map_pad_0_3 = zeroPad(feature_map3) feature_pool_3 = max_pool(feature_map_pad_0_3) print(feature_pool_1.size()) print(feature_pool_1 / 9) print(feature_pool_2 / 9) print(feature_pool_3 / 9) print(--------------- 激活 ---------------) activation_function = nn.ReLU() feature_relu1 = activation_function(feature_map1) feature_relu2 = activation_function(feature_map2) feature_relu3 = activation_function(feature_map3) print(feature_relu1 / 9) print(feature_relu2 / 9) print(feature_relu3 / 9)