使用的Tensorflow版本:2.13.0
错误详情:
ValueError Traceback (most recent call last)
Cell In \[481\], line 1
\----\> 1 titanic_model.save('titanic_model.keras')
2 reloaded = tf.keras.models.load_model('titanic_model.keras')
File \~\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\keras\\src\\utils\\traceback_utils.py:70, in filter_traceback.\<locals\>.error_handler(\*args, \*\*kwargs)
67 filtered_tb = \_process_traceback_frames(e.__traceback__)
68 # To get the full stack trace, call:
69 # `tf.debugging.disable_traceback_filtering()`
\---\> 70 raise e.with_traceback(filtered_tb) from None
71 finally:
72 del filtered_tb
File \~\\AppData\\Local\\Programs\\Python\\Python311\\Lib\\site-packages\\keras\\src\\layers\\preprocessing\\index_lookup.py:839, in IndexLookup.save_assets(self, dir_path)
838 def save_assets(self, dir_path):
\--\> 839 if self.input_vocabulary:
840 # Vocab saved in config.
841 # TODO: consider unifying both paths.
842 return
843 vocabulary = self.get_vocabulary(include_special_tokens=True)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
执行此操作时出现上述错误:
titanic_model.save('titanic_model.keras')
看起来发生该错误是因为将词汇表与在 StringLookup 期间创建的 bool 进行比较,我正在按如下方式创建该布尔值:
for name, input_ in inputs.items():
if input_.dtype == tf.float32:
continue
lookup = layers.StringLookup(vocabulary = np.unique(titanic_features[name]), output_mode = 'one_hot', name = "string_lookup_" + name) #
# lookup.adapt(titanic_features[name])
print(lookup.get_vocabulary())
# one_hot = layers.CategoryEncoding(num_tokens = lookup.vocabulary_size())
x = lookup(input_)
# x = one_hot(x)
all_inputs.append(x)
如果我尝试通过如下所示使图层适应特征来学习词汇,那么错误就会消失:
for name, input_ in inputs.items():
if input_.dtype == tf.float32:
continue
lookup = layers.StringLookup(output_mode = 'one_hot', name = "string_lookup_" + name) #vocabulary = np.unique(titanic_features[name]),
lookup.adapt(titanic_features[name])
print(lookup.get_vocabulary())
# one_hot = layers.CategoryEncoding(num_tokens = lookup.vocabulary_size())
x = lookup(input_)
# x = one_hot(x)
all_inputs.append(x)
使用的Python版本:3.11.0
请找到我附在此处的笔记本:
https://colab.research.google.com/drive/1okGXF8kr7faeGijPittyAqJt9i60SUKn?usp=sharing
我在尝试使用 TextVectorization 预处理层保存模型时遇到了同样的问题。感谢您的解决方案,它对我有用!
tf:2.13.0 蟒蛇:3.10
我确实发现了这个问题。它似乎在新版本中已修复。
错误在包中https://github.com/keras-team/keras/blob/v3.0.0/keras/layers/preprocessing/index_lookup.py
在新版本中,代码如下所示: “ def save_assets(self, dir_path): 如果 self.input_vocabulary 不是 None:“
而在旧版本中,代码是: “ def save_assets(self, dir_path): if self.input_vocabulary: "
在旧版本中,它检查词汇表是否为“true”,在新版本中,它会正确检查词汇表是否存在。