首页 > 解决方案 > 使用 tensorflow 模型的预测

问题描述

我使用以下代码对新数据进行预测:

def predict(dfeval, importedModel):
    colNames = dfeval.columns
    dtypes = dfeval.dtypes
    predictions = []
    for row in dfeval.iterrows():
        example = tf.train.Example()
        for i in range(len(colNames)):
            dtype = dtypes[i]
            colName = colNames[i]
            value = row[1][colName]
            if dtype == "object":
                value = bytes(value, "utf-8")
                example.features.feature[colName].bytes_list.value.extend(
                    [value])
            elif dtype == "float":
                example.features.feature[colName].float_list.value.extend(
                    [value])
            elif dtype == "int":
                example.features.feature[colName].int64_list.value.extend(
                    [value])
    predictions.append(
      importedModel.signatures["predict"](
        examples=tf.constant([example.SerializeToString()])))
    return predictions

val = predict(dfeval, imported)
val

它提供:

[{'predictions': <tf.Tensor: shape=(1, 1), dtype=float32, numpy=array([[0.24904668]], dtype=float32)>}]

然后我可以通过以下方式打印值:

tf.print(val)

[{'预测':[[0.249046683]]}]

但我想在未来的计算中使用该值,例如:

val + 300

我希望得到回报:

300.249046683

但截至目前,我找不到提取和使用预测的方法。

标签: pythontensorflow

解决方案


你可以像这样得到它:

val[0]['predictions'][0][0]

推荐阅读