【问题标题】:What is Tensorflow equivalent of pytorch's conv1d?什么是 pytorch 的 conv1d 的 Tensorflow 等价物?
【发布时间】:2019-11-11 07:10:25
【问题描述】:

只是想知道如何在 tensorflow 中执行一维卷积。具体来说,希望将此代码替换为 tensorflow:

inputs = F.pad(inputs, (kernel_size-1,0), 'constant', 0)

output = F.conv1d(inputs, weight, padding=0, groups=num_heads)

【问题讨论】:

  • TF 1.xx 还是 TF 2.0?
  • TF 版本 1.13.1!

标签: python tensorflow pytorch


【解决方案1】:

Tensorflow 相当于 PyTorch 的

torch.nn.functional.conv1d()tf.nn.conv1d()torch.nn.functional.pad()tf.pad()

例如:

(PyTorch 代码)

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.]]])

(张量流代码)

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)>

【讨论】:

    猜你喜欢
    • 2022-06-22
    • 2020-12-28
    • 1970-01-01
    • 2019-08-29
    • 1970-01-01
    • 2017-01-14
    • 2022-08-21
    • 2019-03-24
    • 1970-01-01
    相关资源
    最近更新 更多