python - TensorFlow随机森林获取标签作为预测输出

标签 python tensorflow tensorflow-decision-forests

我正在使用 TensorFlow 决策林根据几个参数来预测合适的裁剪。如何让 Predict() 方法返回标签?

我正在使用this用于训练的数据集

我的代码

import tensorflow_decision_forests as tfdf
import tensorflow as tf
import pandas as pd
import numpy as np

df = pd.read_csv("Crop_recommendation.csv")

#TensorFlow dataset
train_ds = tfdf.keras.pd_dataframe_to_tf_dataset(df,label="label")

# Train the model
model = tfdf.keras.RandomForestModel()
model.fit(train_ds)
print(model.summary())

pd_serving_dataset = pd.DataFrame({
    "N": [83],
    "P": [45],
    "K" : [30],
    "temperature" : [25],
    "humidity" : [80.3],
    "ph" : [6],
    "rainfall" : [200.91],
})

tf_serving_dataset = tfdf.keras.pd_dataframe_to_tf_dataset(pd_serving_dataset)
prediction = model.predict(tf_serving_dataset)

print(prediction)

我的输出

1/1 [==============================] - 0s 38ms/step
[[0.         0.         0.         0.         0.02333334 0.07666666
  0.04666667 0.         0.08333332 0.         0.         0.
  0.         0.         0.         0.         0.         0.
  0.         0.         0.7699994  0.        ]]

预期产量大米

最佳答案

对于分类问题,Tensorflow 决策森林以 numpy 数组的形式返回每个类的概率。如果您需要类名称,则必须找到概率最高的类并将其映射回其名称。

由于 Keras 期望类名是整数,因此 TF-DF 在 tfdf.keras.pd_dataframe_to_tf_dataset 期间默默地转换它们。通过排序和映射到整数。因此,要获取名称,您必须恢复映射。总的来说,你会得到

classification_names = df["label"].unique().tolist().sort()
prediction = model.predict(tf_serving_dataset)
class_predictions = list(map(lambda x: classification_names[x] , list(np.argmax(prediction, axis=1))))
# Since you only predicted a single example, class_predictions = ['rice']

警告:TF-DF 可能会改变方式 tfdf.keras.pd_dataframe_to_tf_dataset在未来的某个时刻将类映射到整数。通过预处理 pandas 数据帧来自己执行映射会更谨慎

classes = df[label].unique().tolist()
print(f"Label classes: {classes}")

dataset_df[label] = df[label].map(classes.index)

有关如何使用 TF-DF 进行(快速)预测的更多信息,您还可以查看 TF-DF predictions colab .

关于python - TensorFlow随机森林获取标签作为预测输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75287621/

相关文章:

python - 我可以将所有 tensorflow slim 模型转换为 tflite 吗?

python - 如何使用 Python 的 CFFI 传递指向 C 函数的指针?

python - 使用 matplotlib 中的值更改点的维度

python - NameError : global name "total" is not defined, 但它是

python - 错误 libtorch_python.so : cannot open shared object file: No such file or directory

python - 如何运行以张量为范围的循环? (在 tensorflow 中)

python - 将多个参数传递给 tf.data.Datasets.from_generator 中的生成器