InvalidArgumentError:维度0的切片索引0超出了序列模型中自定义层的界限



获取此错误

InvalidArgumentError: slice index 0 of dimension 0 out of bounds. [Op:StridedSlice] name: strided_slice/

与第一个密集层的输入相比,调用方法的输出中存在一些问题。将输出从"tf.constant[results]"更改为"tf.coconstant[results]"只会出现错误"min_ndim=2",得到ndim=1。

class TextVectorizationLayer(keras.layers.Layer):
def __init__(self, **kwargs):
super().__init__(**kwargs, dynamic=True)
self.table = {}
def call(self, inputs, **kwargs):
review = preprocess(inputs)
results = []
for word in self.table:
if word in review:
results.append(self.table.get(word))
else:
results.append(0)
return tf.constant([results])
def adapt(self, data, count):
reviews = [preprocess(r) for (r,_) in data]
for review in reviews:
for word in review.numpy():
self.table[word] = 
self.table.get(word, 0) + 1
self.table = OrderedDict(sorted(self.table.items(),
key=lambda x: x[1],
reverse=True)[:count])
return self.table
sample_string_batches = train_set.take(25)
vectorization = TextVectorizationLayer()
words = vectorization.adapt(sample_string_batches, 400)
model = keras.models.Sequential([
vectorization,
keras.layers.Dense(100, activation="relu"),
keras.layers.Dense(1, activation="sigmoid"),
])
model.compile(loss="binary_crossentropy", optimizer="nadam",
metrics=["accuracy"])
model.fit(train_set, epochs=5, validation_data=val_set)

Train and Val Data的形状为((,((

Model: "sequential_15"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
text_vectorization_layer_10  multiple                  0         
_________________________________________________________________
dense_30 (Dense)             multiple                  40100     
_________________________________________________________________
dense_31 (Dense)             multiple                  101       
=================================================================
Total params: 40,201
Trainable params: 40,201

不可训练参数:0

请检查层的"input_ shape";参数,因为它将被提供有(0,x(形状。从而得到索引0 的错误

最新更新