我尝试在linspace上调用TensorFlow模型,但似乎连一个非常简单的示例(基于https://www.tensorflow.org/api_docs/python/tf/keras/Model)都无法正常工作:
import tensorflow as tf
class FeedForward(tf.keras.Model):
def __init__(self):
super().__init__()
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu, name='lyr1')
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax, name='lyr2')
def call(self, inputs, training=False):
x = self.dense1(inputs) # <--- error here
return self.dense2(x)
model = FeedForward()
batchSize = 2048
preX = tf.linspace(0.0, 10.0, batchSize)
model(preX, training=True)
我得到以下错误(在上面指示的行中):
ValueError: Exception encountered when calling layer "feed_forward_87" (type FeedForward).
Input 0 of layer "lyr1" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (2048,)
Call arguments received:
• inputs=tf.Tensor(shape=(2048,), dtype=float32)
• training=True
我已尝试添加输入图层
import tensorflow as tf
class FeedForward(tf.keras.Model):
def __init__(self):
super().__init__()
self.inLyr = tf.keras.layers.Input(shape=(2048,), name='inp')
self.dense1 = tf.keras.layers.Dense(4, activation=tf.nn.relu, name='lyr1')
self.dense2 = tf.keras.layers.Dense(5, activation=tf.nn.softmax, name='lyr2')
def call(self, inputs, training=False):
x = self.inLyr(inputs) # <---- error here
x = self.dense1(x)
return self.dense2(x)
model = FeedForward()
batchSize = 2048
preX = tf.linspace(0.0, 10.0, batchSize)
model(preX, training=True)
但是错误就变成了
TypeError: Exception encountered when calling layer "feed_forward_88" (type FeedForward).
'KerasTensor' object is not callable
Call arguments received:
• inputs=tf.Tensor(shape=(2048,), dtype=float32)
• training=True
任何帮助都很感激。
2条答案
按热度按时间bqucvtff1#
您不需要显式的
Input
图层。您只是缺少一个维度。请尝试使用tf.expand_dims
来获取所需的输入形状(batch_size, features)
:或者使用
Input
图层:whlutmcx2#
我也从你的回复中学习,发现他们的Fn可能需要像desns_1和dense_2那样工作,然后我把它改造成一个序列的模型。
对于错误,这是要修复!
[样品]:
[输出]: