我正在尝试将this functionality从Python移植到.NET Core上的C#,以查看是否可以从我知道的静态类型语言中使用Tensorflow。
为此,我使用this framework,它包装了Tensorflow C ++ API。该API不包含函数conv2d_transpose
,因此我正在寻找一种用C ++ API中实际存在的函数替换它的方法。
我尝试挖掘Tensorflow的源代码,以查看是否可以找到conv2d_transpose
的实现,并找到this code并将其引向this code,在我看来,这类似于以下内容是实际的肉:
with ops.name_scope(name, "conv2d_transpose", [input, filter, output_shape]) as name:
if data_format is None:
data_format = "NHWC"
channel_index = 1 if data_format.startswith("NC") else 3
strides = _get_sequence(strides, 2, channel_index, "strides")
dilations = _get_sequence(dilations, 2, channel_index, "dilations")
return gen_nn_ops.conv2d_backprop_input(
input_sizes=output_shape,
filter=filters,
out_backprop=input,
strides=strides,
padding=padding,
data_format=data_format,
dilations=dilations,
name=name)
我翻译了以下Python代码:
def _conv_tranpose_layer(net, num_filters, filter_size, strides):
weights_init = _conv_init_vars(net, num_filters, filter_size, transpose=True)
batch_size, rows, cols, in_channels = [i.value for i in net.get_shape()]
new_rows, new_cols = int(rows * strides), int(cols * strides)
new_shape = [batch_size, new_rows, new_cols, num_filters]
tf_shape = tf.stack(new_shape)
strides_shape = [1,strides,strides,1]
net = tf.nn.conv2d_transpose(net, weights_init, tf_shape, strides_shape, padding='SAME')
net = _instance_norm(net)
return tf.nn.relu(net)
到以下C#代码:
private Tensor _conv_transpose_layer(Tensor net, int num_filters, int filter_size, int strides)
{
RefVariable weights_init = _conv_init_vars(net, num_filters, filter_size, transpose: true);
int batch_size = net.shape[0];
int rows = net.shape[1];
int cols = net.shape[2];
int in_channels = net.shape[3];
int new_rows = rows * strides;
int new_cols = cols * strides;
int[] new_shape = new int[] { batch_size, new_rows, new_cols, num_filters };
Tensor tf_shape = tf.stack(new_shape);
int[] strides_shape = new int[] { 1, strides, strides, 1 };
//net = tf.nn.conv2d_transpose(net, weights_init, tf_shape, strides_shape, "SAME");
net = Tensorflow.Operations.gen_nn_ops.conv2d_backprop_input(new Tensorflow.Operations.Conv2dParams()
{
InputSizes = tf_shape,
Filter = weights_init,
OutBackProp = net,
Strides = strides_shape,
DataFormat = "NHWC",
Dilations = null,
Name = null
});
net = _instance_norm(net);
return tf.nn.relu(net);
}
我本可以使用this post的答案来解决我的问题,但是我不知道如何将这些答案集成到我正在构建的图形中。特别是因为它们包含循环或Session.run
我对ML知之甚少,无法真正验证此代码的结果,并且我没有足够的计算资源来尝试我能想到的一切。
请告诉我我的翻译是否有意义,以及在哪里可以找到有关这些操作为何/如何发生联系的更多信息。
谢谢。