【问题标题】:how to apply numpy function on a tensor with unknown shape如何在形状未知的张量上应用 numpy 函数
【发布时间】:2021-12-01 23:58:54
【问题描述】:

我正在尝试构建一个模仿 NumPy 预构建切片功能的 Keras 层,例如 ([np.tile][1])。我已经尝试了以下代码,但它没有工作

import tensorflow as tf
from tensorflow import keras
from keras import Input

class Tile(Layer):
    def __init__(self,repeat, **kwargs):
        self.repeat = repeat
        super(Tile,self).__init__(**kwargs)

    def call(self, x):
        return np.tile(x,self.repeat)

input= Input(shape= (3,))
repeat = (1,2)
x = Tile(repeat)(input)
model = keras.Model(input,x)
print(model(tf.ones(3,)))

错误输出

---> x = Tile(repeat)(input)
NotImplementedError: Cannot convert a symbolic Tensor (Placeholder:0) to a numpy array. This error may indicate that you're trying to pass a Tensor to a NumPy call, which is not supported

我认为这个问题与批量大小的未知维度有关,但我不知道如何处理它。有人可以帮忙吗?

【问题讨论】:

    标签: python numpy tensorflow keras


    【解决方案1】:

    这里有几个问题。

    1. Keras 符号张量无法使用 NumPy 进行操作。要么急切地运行,要么使用 Tensorflow 操作
    2. 您需要为模型提供 2d 输入

    试试这个:

    import tensorflow as tf
    import numpy as np
    
    
    class Tile(tf.keras.layers.Layer):
        def __init__(self, repeat, **kwargs):
            self.repeat = repeat
            super(Tile, self).__init__(**kwargs)
    
        def call(self, x):
            return tf.tile(x, self.repeat)
    
    
    input = tf.keras.Input(shape=(3,))
    repeat = (1, 2)
    x = Tile(repeat)(input)
    model = tf.keras.Model(input, x)
    print(model(tf.ones((1, 3))))
    
    tf.Tensor([[1. 1. 1. 1. 1. 1.]], shape=(1, 6), dtype=float32)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-04
      • 2017-10-16
      • 2020-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多