做免费推广网站,重庆关键词优化平台,能打开各种网站的浏览器下载合集,广西做网站CNN卷积神经网络
基础概念#xff1a;
以卷积操作为基础的网络结构#xff0c;每个卷积核可以看成一个特征提取器。
思想#xff1a;
每次观察数据的一部分#xff0c;如图#xff0c;在整个矩阵中只观察黄色部分33的矩阵#xff0c;将这【33】矩阵(点乘)权重得到特…CNN卷积神经网络
基础概念
以卷积操作为基础的网络结构每个卷积核可以看成一个特征提取器。
思想
每次观察数据的一部分如图在整个矩阵中只观察黄色部分3×3的矩阵将这【3×3】矩阵·(点乘)权重得到特征矩阵的第一项然后进行平移进行第二项的计算。依此类推得到最后的特征矩阵。
利用Pytorch框架实现CNN
import torch
import torch.nn as nn
import numpy as np
使用pytorch实现CNN
不考虑偏差值
class TorchCNN(nn.Module):def __init__(self, in_channel, out_channel, kernel):super(TorchCNN, self).__init__()self.layer nn.Conv2d(in_channel, out_channel, kernel, biasFalse)def forward(self, x):return self.layer(x)x np.array([[0.1, 0.2, 0.3, 0.4],[-3, -4, -5, -6],[5.1, 6.2, 7.3, 8.4],[-0.7, -0.8, -0.9, -1]]) #网络输入#torch实验
in_channel 1 #单通道(NLP中一般用单通道)
out_channel 3 #多少个卷积核(每一个卷积核代表一个独立的权重)
kernel_size 2 #2*2的方块(功能就是图中黄色[3×3]矩阵)
torch_model TorchCNN(in_channel, out_channel, kernel_size)
# print(torch_model.state_dict())
torch_w torch_model.state_dict()[layer.weight]
# print(torch_w.numpy().shape)
torch_x torch.FloatTensor([[x]])
#权重是4维输入应该也为四维通过多一个[]将输入由三维变成四维
output torch_model.forward(torch_x)
output output.detach().numpy()
print(output, output.shape, torch模型预测结果\n)自定义模型代码实现CNN
采用自定义模型实现CNN不考虑偏差值因为要与Pytorch框架结果相对比需要调取在Pytorch模型中的输入和随机权重。因此如果要运行须将此代码放在Pytorch框架下运行。 手动实现简单的神经网络
与Pytorch对比实验#自定义CNN模型
class DiyModel:def __init__(self, input_height, input_width, weights, kernel_size):self.height input_heightself.width input_widthself.weights weightsself.kernel_size kernel_sizedef forward(self, x):output []for kernel_weight in self.weights:kernel_weight kernel_weight.squeeze().numpy()#weight取出来时是[1×2×2]通过squeeze变成[2×2]然后变成numpy取出kernel_output np.zeros((self.height - kernel_size 1, self.width - kernel_size 1)) #全0输出矩阵for i in range(self.height - kernel_size 1):for j in range(self.width - kernel_size 1):window x[i:ikernel_size, j:jkernel_size] #x是原始输入 剩下的是矩阵索引方法kernel_output[i, j] np.sum(kernel_weight * window) #np.dot ! x*y x*y是点乘(对应位置相乘)output.append(kernel_output)return np.array(output)diy_model DiyModel(x.shape[0], x.shape[1], torch_w, kernel_size)
output diy_model.forward(x)
print(output, diy模型预测结果)
最终对比结果 可以清楚看到Pytorch框架下的结果与自定义框架下的结果相同。