什么是 pytorch 的 conv1d 的 Tensorflow 等价物? [英] What is Tensorflow equivalent of pytorch's conv1d?
本文介绍了什么是 pytorch 的 conv1d 的 Tensorflow 等价物?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
只是想知道如何在 tensorflow 中执行一维卷积.具体来说,希望将此代码替换为 tensorflow:
Just wondering how I can perform 1D convolution in tensorflow. Specifically, looking to replace this code to tensorflow:
inputs = F.pad(inputs, (kernel_size-1,0), 'constant', 0)
output = F.conv1d(inputs, weight, padding=0, groups=num_heads)
推荐答案
Tensorflow 相当于 PyTorch 的
Tensorflow equivalent of PyTorch's
torch.nn.functional.conv1d()
是tf.nn.conv1d()
和 torch.nn.functional.pad()
是 tf.pad()
.
例如:
(PyTorch 代码)
(PyTorch code)
import torch.nn as nn
import torch
inputs = torch.tensor([1, 0, 2, 3, 0, 1, 1], dtype=torch.float32)
filters = torch.tensor([2, 1, 3], dtype=torch.float32)
inputs = inputs.unsqueeze(0).unsqueeze(0) # torch.Size([1, 1, 7])
filters = filters.unsqueeze(0).unsqueeze(0) # torch.Size([1, 1, 3])
conv_res = F.conv1d(inputs, filters, padding=0, groups=1) # torch.Size([1, 1, 5])
pad_res = F.pad(conv_res, (1, 1), mode='constant', value=0) # torch.Size([1, 1, 7])
输出:
tensor([[[ 0., 8., 11., 7., 9., 4., 0.]]])
(Tensorflow 代码)
(Tensorflow code)
import tensorflow as tf
tf.enable_eager_execution()
i = tf.constant([1, 0, 2, 3, 0, 1, 1], dtype=tf.float32)
k = tf.constant([2, 1, 3], dtype=tf.float32, name='k')
data = tf.reshape(i, [1, int(i.shape[0]), 1], name='data')
kernel = tf.reshape(k, [int(k.shape[0]), 1, 1], name='kernel')
res = tf.nn.conv1d(data, kernel, 1, 'VALID')
res = tf.pad(res[0], [[1, 1], [0, 0]], "CONSTANT")
输出:
<tf.Tensor: id=555, shape=(7, 1), dtype=float32, numpy=
array([[ 0.],
[ 8.],
[11.],
[ 7.],
[ 9.],
[ 4.],
[ 0.]], dtype=float32)>
这篇关于什么是 pytorch 的 conv1d 的 Tensorflow 等价物?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文