总的来说,我对 Tensorflow 和机器学习相当陌生,但我已经足够了解我已经构建了一个小模型。虽然,当加载并使用 model.predict
时,我收到属性错误:
import tensorflow as tf
import numpy as np
checkpoint_path = "training_1/cp.ckpt"
# Hyperparamters
vocab_size = 2000
embedding_dim = 16
max_length = 1
trunc_type = "post"
padding_type = "post"
oov_tok = "<OOV>"
training_size = 100
model = tf.keras.Sequential([
tf.keras.layers.Embedding(
vocab_size, embedding_dim, input_length=max_length),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
tf.keras.layers.Dense(128, activation="relu"),
tf.keras.layers.Dense(3, activation="softmax")
])
# Compile the model
model.compile(loss="sparse_categorical_crossentropy",
optimizer="adam", metrics=["accuracy"])
model.load_weights(checkpoint_path)
test = ["Example of text here"]
prediction = model.predict(test)
print(prediction)
Traceback (most recent call last):
File "./ModelTest.py", line 36, in <module>
prediction = model.predict(test)
File "/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 1060, in predict
x, check_steps=True, steps_name='steps', steps=steps)
File "/lib/python3.7/site-packages/tensorflow/python/keras/engine/training.py", line 2651, in _standardize_user_data
exception_prefix='input')
File "/lib/python3.7/site-packages/tensorflow/python/keras/engine/training_utils.py", line 334, in standardize_input_data
standardize_single_array(x, shape) for (x, shape) in zip(data, shapes)
File "/lib/python3.7/site-packages/tensorflow/python/keras/engine/training_utils.py", line 334, in <listcomp>
standardize_single_array(x, shape) for (x, shape) in zip(data, shapes)
File "/lib/python3.7/site-packages/tensorflow/python/keras/engine/training_utils.py", line 265, in standardize_single_array
if (x.shape is not None and len(x.shape) == 1 and
AttributeError: 'str' object has no attribute 'shape'
最佳答案
确保您提供的输入格式适合您构建的模型。在您的情况下,Embedding
层需要一个 2D 张量。数据应该是一个 numpy 数组,如下所示:[[0, 2, 64], [24, 6, 8]]
。每个数字代表一个单词,每个数字序列代表一个短语。整个张量代表一批序列。在我的示例中,这是一批 2 个序列,每个序列包含 3 个单词。
您需要做的是使用您正在加载的模型的正确词汇来标记“此处的文本示例”
。完成后,您将获得一个类似于 [[3, 8, 4, 6]]
的数组,其中每个数字对应于 “此处的文本示例”中的单词之一“
。如何正确地标记它取决于它所训练的数据是如何标记的,如果不知道您从哪里获得training_1/cp.ckpt
,我们就不知道这一点。
关于python - 根据预测,我加载的模型给了我一个 AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57811573/