【问题标题】:Is there an equivalent of pytorch.nn.functional.unfold() in keras or tensorflow?在 keras 或 tensorflow 中是否有 pytorch.nn.functional.unfold() 的等价物?
【发布时间】:2020-07-29 15:09:13
【问题描述】:

我想在 keras 中执行类似的操作。但是,我无法在 keras 中进行展开操作。我尝试使用 conv1D 层,但无法弄清楚。任何帮助将不胜感激

'''

import numpy as np
import torch

x = torch.tensor(np.random.rand(25,100,24))   # tensor of shape (batch_size, seq_length,feature_dim)
x = x.unsqueeze(1) # shape=(25,1,100,24)

import torch.nn.functional as F
x = F.unfold(x,(5, 24), stride=(1,24),dilation=(1,1)) #shape (25,120,96)

'''

【问题讨论】:

标签: tensorflow keras pytorch


【解决方案1】:

我认为没有。但你可以做一件事。使用张量展开。创建一个展开输入数组的函数。然后使用该功能在 keras 或 tf2.0 中创建一个 lambda 层。假设您有输入数组 X :

 X = np.array([[[ 0,  1],
                   [ 2,  3],
                   [ 4,  5],
                   [ 6,  7]],
    
                  [[ 8,  9],
                   [10, 11],
                   [12, 13],
                   [14, 15]],
    
                  [[16, 17],
                   [18, 19],
                   [20, 21],
                   [22, 23]]])

要展开张量,只需使用 TensorLy 的展开函数:

> from tensorly import unfold unfold(X, 0)
>> array([[ 0,  1,  2,  3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20, 21, 22, 23]])

现在创建一个接受输入数组并返回展开的函数 数组

def unfold(X):
        return unfold(X, 0)

现在在keras中使用这个函数作为一个层

from keras.layers import Lambda
from keras.models import Sequential

model = Sequential()
model.add(....some_layer....)
model.add(....anotenter code hereher_layer....)
model.add(Lambda(unfold))   <<<<=== using our unfold function as keras layer
model.add(...more_layers..)

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2022-08-21
    • 1970-01-01
    • 2015-11-03
    • 2012-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多