首页 > 解决方案 > DistilBERT 预测输出 - “TypeError:只有大小为 1 的数组可以转换为 Python 标量”

问题描述

我正在尝试应用 DistilBERT 模型来创建预测,无论句子是声明、前提还是非争论(3 个输出)

但是,当我应用模型并希望使用以下代码创建预测时:

def predict_sentences_from_list(sentence_list, text, tokenizer, model, label_list):
    predictions_dict = {key: [] for key in ["sentences"]}
    c_counter = 0
    p_counter = 0
    feedback_list = []
    result = FRE(nlp(text))
    print("FRE:", result)

    for sentence in sentence_list:
        predict_input = tokenizer.encode(sentence,
                                  truncation=True,
                                  padding=True,
                                  return_tensors="tf"
                                  )
        tf_output = model.predict(predict_input)[0][0]
        print("tf_output", tf_output)

        tf_output = tf_output.astype(float)
        print("tf_output_new", tf_output)
        tf_prediction = tf.exp(tf_output) / tf.reduce_sum(tf.exp(tf_output), axis=0).numpy()
        tf_prediction = tf_prediction.numpy()
        print("tf_prediction", tf_prediction)
        index = int(tf.math.argmax(tf_prediction).numpy())

我收到以下错误代码:

TypeError: only size-1 arrays can be converted to Python scalars

并且不知何故是多阵列输出,我无法处理。(见下面的例子)

tf_output [[ 0.21984343 -0.5467574   0.0040243  ... -0.19792344  0.75051785
   0.42536935]
 [ 0.40001354 -0.33571464  0.2520863  ... -0.169448    0.74237293
   0.10507141]
 [ 0.5038232  -0.5277173   0.40050912 ... -0.32889333  0.52978003
   0.29682326]
 ...
 [ 0.03361291 -0.15118203  0.5666938  ... -0.5183538   0.46048933
   0.26265204]
 [ 0.59308946 -0.13700745 -0.04438984 ... -0.04448561 -0.32723922
  -0.01682709]
 [ 0.58926195 -0.02571652  0.30869782 ...  0.0776237   0.13490912
   0.22816204]]

有没有人有经验如何处理它?

谢谢!

标签: pythonbert-language-modelhuggingface-tokenizersdistilbert

解决方案


推荐阅读