pytorch

前言:把某个环境引入jupyter的方法 跳转

https://blog.csdn.net/Ever_____/article/details/136596213 # 加载数据

Dataset类

把文件转化为torch的数据集对象,类似于写一个脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from torch.utils.data import Dataset
import os
from PIL import Image
class MyDataset(Dataset):
def __init__(self,root_dir,label_dir):
self.root_dir = root_dir
self.label_dir = label_dir
self.path = os.path.join(self.root_dir,self.label_dir)
#返回的是文件和子文件夹的名字列表。
self.img_list = os.listdir(self.path)
def __getitem__(self,idx):
img_name = self.img_list[idx]
img_item_path = os.path.join(self.root_dir,self.label_dir,img_name)
img = Image.open(img_item_path)
label = self.label_dir
return img, label
def __len__(self):
return len(self.img_list)

root_dir = 'dataset/train'
ants_lavel_dir = 'ants'
bees_label_dir = 'bees'
ants_dataset = MyDataset(root_dir,ants_lavel_dir)
bees_dataset = MyDataset(root_dir,bees_label_dir)

Dataloader类

搭建模型

nn.Module类

常用的的包torch.nn
神经网络的基类Module,定义的模型都需要集成该类nn.Module
自己定义的模型需要实现__init__和forward函数

1
2
3
4
5
6
7
8
9
10
11
12
13
import torch
from torch import nn
class Mynet(nn.Module):
def __init__(self):
super().__init__()

def forward(self, input):
output = input +1
return output
net = Mynet()
x = torch.tensor(1.0)
myout = net(x)
print(myout)

网络设计

线性连接层

1
2
3
4
5
6
7
8
9
10
class Mynet(nn.Module):
def __init__(self):
# 调用父类初始化方法
super(Mynet,self).__init__()
# 定义一个全连接层,将输入的 196608 个特征映射到 10 个输出特征
self.linear1 = Linear(196608,10)

def forward(self,input):
output = self.linear1(input)
return output

flatten

卷积层

池化层

损失函数

传播


pytorch
http://example.com/2024/06/10/编程语言/pytorch/
作者
bradin
发布于
2024年6月10日
许可协议