【问题标题】:how to predict new inputs using a tensorflow model如何使用张量流模型预测新输入
【发布时间】:2023-03-15 03:21:01
【问题描述】:

有很多关于构建 tensorflow 模型的好教程,我成功地创建了一个准确度很高的模型。但是,还有 2 个问题。

在我的数据集中有很多类,我试着这样说明:

label - text
--------------------
A - this is a A text
B - this is a B text
C - this is a C text
...
Z - this is a Z text
...
ZA - this is a ZA text
...

现在我想建立一个倾向于对文本进行分类的网络。我明白,我必须提供一组固定的标签,因为网络需要有固定数量的“输出神经元”。因此,出于学习目的,我开始为 3 个类 A、B 和 C 构建一个网络。我只为网络提供了相应的行(A、B、C),我得到了一个可以识别 A、B 的模型, C 具有良好的准确性。

现在我想预测新文本并希望得到这样的输出:

input text -> predicted label
----------------------------
this is a B text -> B   // successful prediction
this is a xyz text -> ? // cannot be predicted, because not learned

我如何为尚未学习的课程实现“不可预测”?

总之,我获得一个添加了预测列的 csv 文件可能有点笨拙。你能告诉我如何做得更好吗?

import pandas as pd
df = pd.read_parquet(path)


#print(df)
#label = df['kategorie'].fillna("N/A")
text = df['text'].fillna("")

text_padded = tokenize_and_pad(text)


# Predictions
probability_model = tf.keras.Sequential([model, 
                                         tf.keras.layers.Softmax()])
predictions = probability_model.predict(text_padded)

# get the predicted labels
# I only achieved this with this loop - there must be a more elegant way???
predictedLabels = []
for prediction in predictions:
    labelID = np.argmax(prediction)
    predictedLabel = label_encoder.inverse_transform([labelID])
    predictedLabels.append(predictedLabel)


# add the new column to the dataframe
# the prediction is accurate for the learned labels
# but totally wrong for the labels, that I excluded from the learning
df['predictedLabels'] = predictedLabels

# todo: write to file

【问题讨论】:

    标签: python tensorflow prediction


    【解决方案1】:

    根据您的问题,我了解到您在两个方面需要帮助:

    1. 回答问题,How do I achieve the "not predictable" for the not yet learned classes?

    一个。由于您只想考虑 3 个类,而不是删除与其他类对应的行,您可以将这些列的名称替换为“不可预测”,即,将 'D', 'E', 'F', etc.. 替换为 "Not Predictable"

    b.在 Final Dense Layer 中,将 Neurons 的数量从 3 更改为 4,第 4 类代表 "Not Predictable"

    1. 回答问题,如何将Predictions 写入CSV 文件:

    现在Predictions 已作为Column 添加到DataFrame, df 中,您可以使用该命令将其写入 CSV 文件,

    df.to_csv('My_Predictions.csv')
    

    有关此命令的更多信息,请参考this link

    您访问Labels 的方式看起来很优雅。

    如果您遇到任何其他error,请告诉我,我很乐意为您提供帮助。

    希望这会有所帮助。快乐学习!

    【讨论】:

    • 感谢您的解释。我可以为每一行添加预测正确性的概率吗?
    猜你喜欢
    • 1970-01-01
    • 2017-11-22
    • 1970-01-01
    • 2021-10-07
    • 2019-12-20
    • 2018-12-12
    • 2017-11-21
    • 2022-01-08
    • 1970-01-01
    相关资源
    最近更新 更多