根据下面的reference将动态图模型转为静态图模型后
https://www.paddlepaddle.org.cn/documentation/docs/zh/api_cn/dygraph_cn/TracedLayer_cn.html#tracedlayer
使用paddle2onnx转换时无法通过onnx的checker:
onnx.onnx_cpp2py_export.checker.ValidationError: Nodes in a graph must be topologically sorted, however input 't_14' of node:
input: "t_14" input: "t_15@reshape_y" output: "t_15" op_type: "Add"
代码如下:
import paddle
import paddle.fluid as fluid
import numpy as np
from paddle.fluid.dygraph.nn import Conv2D, Pool2D, Linear
class DCNN(fluid.dygraph.Layer):
def __init__(self, name_scope, num_classes=10):
super(DCNN, self).__init__(name_scope)
name_scope = self.full_name()
# AlexNet与LeNet一样也会同时使用卷积和池化层提取图像特征
# 与LeNet不同的是激活函数换成了‘relu’
self.conv1 = Conv2D(num_channels=3, num_filters=32, filter_size=3, stride=1, padding=1, act='relu')
self.pool1 = Pool2D(pool_size=2, pool_stride=2, pool_type='max')
self.conv2 = Conv2D(num_channels=32, num_filters=16, filter_size=3, stride=1, padding=2, act='relu')
self.pool2 = Pool2D(pool_size=2, pool_stride=2, pool_type='max')
self.conv3 = Conv2D(num_channels=16, num_filters=8, filter_size=3, stride=1, padding=1, act='relu')
self.pool3 = Pool2D(pool_size=2, pool_stride=2, pool_type='max')
self.fc1 = Linear(input_dim=6272, output_dim=1568, act='relu')
self.drop_ratio1 = 0.5
self.fc2 = Linear(input_dim=1568, output_dim=128, act='relu')
self.drop_ratio2 = 0.5
self.fc3 = Linear(input_dim=128, output_dim=num_classes, act='relu')
def forward(self, inputs,label=None):
x = self.conv1(inputs)
x = self.pool1(x)
#print(x.numpy().shape)
x = self.conv2(x)
x = self.pool2(x)
#print(x.numpy().shape)
x = self.conv3(x)
x = self.pool3(x)
#print(x.numpy().shape)
x = fluid.layers.reshape(x, [x.shape[0], -1])
x = self.fc1(x)
x= fluid.layers.dropout(x, self.drop_ratio1)
x = self.fc2(x)
x= fluid.layers.dropout(x, self.drop_ratio2)
x = self.fc3(x)
x = fluid.layers.softmax(x)
if label is not None:
acc = fluid.layers.accuracy(input=x, label=label)
return x, acc
else:
return x
with fluid.dygraph.guard():
model = DCNN("DCNN",num_classes = 39)
#print(model)
#train(model)
in_np = np.random.random([10, 3, 224, 224]).astype('float32')
# 将numpy的ndarray类型的数据转换为Variable类型
input_var = fluid.dygraph.to_variable(in_np)
# 通过 TracerLayer.trace 接口将动态图模型转换为静态图模型
out_dygraph, static_layer = TracedLayer.trace(model, inputs=[input_np])
out_static_graph = static_layer([input_np])
print(len(out_static_graph)) # 1
print(out_static_graph[0].shape) # (2, 10)
save_dirname = './saved_infer_model'
# 将转换后的模型保存
static_layer.save_inference_model(dirname='./saved_infer_model')
找人问了一下, 说您这个问题比较复杂, 请移步到 https://github.com/PaddlePaddle/Paddle/issues
使用issue形式来询问吧.