import paddle
import paddle.nn as nn
# #方法1、内置的模型
# print('飞桨框架内置模型:', paddle.vision.models.__all__)
# # 模型组网并初始化网络
# lenet = paddle.vision.models.LeNet(num_classes=10)
# print(type(lenet))
# # 可视化模型组网结构和参数
# paddle.summary(lenet,(1, 1, 28, 28))
##方法2、paddle.nn.Sequential
# from paddle import nn
# # 使用 paddle.nn.Sequential 构建 LeNet 模型
# lenet_Sequential = nn.Sequential(
# nn.Conv2D(1, 6, 3, stride=1, padding=1),
# nn.ReLU(),
# nn.MaxPool2D(2, 2),
# nn.Conv2D(6, 16, 5, stride=1, padding=0),
# nn.ReLU(),
# nn.MaxPool2D(2, 2),
# nn.Flatten(),
# nn.Linear(400, 120),
# nn.Linear(120, 84),
# nn.Linear(84, 10)
# )
# print(type(lenet_Sequential))
# # 可视化模型组网结构和参数
# paddle.summary(lenet_Sequential,(1, 1, 28, 28))
##方法3
# 使用 Subclass 方式构建 LeNet 模型
class LeNet(nn.Layer):
def __init__(self, num_classes=10):
super().__init__()
self.num_classes = num_classes
# 构建 features 子网,用于对输入图像进行特征提取
self.features = nn.Sequential(
nn.Conv2D(
1, 6, 3, stride=1, padding=1),
nn.ReLU(),
nn.MaxPool2D(2, 2),
nn.Conv2D(
6, 16, 5, stride=1, padding=0),
nn.ReLU(),
nn.MaxPool2D(2, 2))
# 构建 linear 子网,用于分类
if num_classes > 0:
self.linear = nn.Sequential(
nn.Linear(400, 120),
nn.Linear(120, 84),
nn.Linear(84, num_classes)
)
# 执行前向计算
def forward(self, inputs):
x = self.features(inputs)
if self.num_classes > 0:
x = paddle.flatten(x, 1)
x = self.linear(x)
return x
lenet_SubClass = LeNet()
print(type(lenet_SubClass))
# 可视化模型组网结构和参数
params_info = paddle.summary(lenet_SubClass,(1, 1, 28, 28))
print(params_info)
#打印模型参数
for name,param in lenet_SubClass.named_parameters():
print(f"Layer: {name} | Size: {param.shape}")
import paddle
x=paddle.uniform((2,3,8,8),dtype='float32')
print(x.shape)
conv=paddle.nn.Conv2D(3,6,(3,3),2,1)
y=conv(x)
print('卷积之后的结果',y.shape)
pool=paddle.nn.MaxPool2D(3,2,padding=1)
y=pool(x)
print('池化后的结果',y.shape)
linear=paddle.nn.Linear(6,4)
x=paddle.rand((2,6),dtype='float32')
print(x.shape)
y=linear(x)
print('线性层之后的结果',y.shape)
# for _ in dir(paddle.nn):
# print(_)
文章来源地址https://www.toymoban.com/news/detail-715268.html
文章来源:https://www.toymoban.com/news/detail-715268.html
到了这里,关于paddle模型定义的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!