我正在嘗試構建一個 Keras 層,它模仿 NumPy 預構建的 tile 函式,例如([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
我認為這個問題與批量大小的未知維度有關,但我不知道如何處理。有人可以幫忙嗎?
uj5u.com熱心網友回復:
這里有幾個問題。
- 不能用 NumPy 操作 Keras 符號張量。要么急切地運行,要么使用 Tensorflow 操作
- 您需要為模型提供 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/317009.html
下一篇:將元組與其中的陣列進行比較
