如何使用张量流模型预测新输入

how to predict new inputs using a tensorflow model

有很多关于构建 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
...

现在我想建立一个倾向于对文本进行分类的网络。我明白,我必须提供一组固定的标签,因为网络需要有一个固定的 "output neurons"。因此,出于学习目的,我开始只为 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

对于尚未学习的类,如何达到"not predictable"?

总而言之,我获取带有添加预测列的 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

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

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

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

b。在Final Dense Layer中,将Neurons的Number由3改为4,第4个class代表"Not Predictable"

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

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

df.to_csv('My_Predictions.csv')

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

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

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

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