import torch as t from torch import nn from torch.autograd import Variable as V from torch.nn import functional as F from PIL import Image from torchvision.transforms import ToTensor, ToPILImage from matplotlib import pyplot as plt #nn.Module class Linear(nn.Module): #继承nn.Module。用nn.Module实现自己的全连接层 def __init__(self, in_features, out_features): super(Linear, self).__init__() #等价于nn.Module.__init__(self) self.w = nn.Parameter(t.randn(in_features, out_features)) self.b = nn.Parameter(t.randn(out_features)) def forward(self, x): x = x.mm(self.w) return x + self.b.expand_as(x) # layer = Linear(4, 3) # input = V(t.randn(2, 4)) # output = layer(input) #等价于layers.__call__(input),在__call__函数中,主要调用的是layer.forward(x) # # print(output) # for name, parameter in layer.named_parameters(): #Module中的可学习参数可通过named_parameters()或者parameters()返回迭代器 # print(name, parameter) #w and b class Perceptron(nn.Module): #多层感知机 def __init__(self, in_features, hidden_features, out_features): nn.Module.__init__(self) self.layer1 = Linear(in_features, hidden_features) self.layer2 = Linear(hidden_features, out_features) def forward(self, x): x = self.layer1(x) x = t.sigmoid(x) return self.layer2(x) # perceptron = Perceptron(3, 4, 1) # for name, param in perceptron.named_parameters(): # print(name, param.size()) ##########################常用的神经网络层############################# #图像相关层 to_tensor = ToTensor() #img -> tensor to_pil = ToPILImage() cat = Image.open(r'C:\Users\45840\Pictures\Saved Pictures\cat.jpg') # plt.imshow(cat) # plt.show() # print(cat) # cat = cat.convert('L') #转换为灰度图像 # plt.imshow(cat) # plt.show() input = to_tensor(cat).unsqueeze(0) #将数据伪装成batch=1的batch # print(input.shape) kernel = t.ones(3, 3)/-9. kernel[1][1] = 1 conv = nn.Conv2d(1, 1, (3, 3), 1, bias=False) conv.weight.data = kernel.view(1, 1, 3, 3) # out = conv(V(input)) #卷积操作 # plt.imshow(to_pil(out.data.squeeze(0))) # plt.show() pool
Pytorch入门与实践——神经网络工具箱
最新推荐文章于 2023-11-06 09:34:09 发布
本文介绍了PyTorch中的神经网络基础,包括自定义全连接层、多层感知机、常用的神经网络层如卷积层、池化层、批归一化层、Dropout层。还展示了如何使用Sequential构建模型,以及激活函数、损失函数和优化器的使用。最后,通过ResNet实例展示了深度学习模型的构建过程。
摘要由CSDN通过智能技术生成