如何使用自定义训练的 keras 模型进行预测

尼基塔

我是 TensorFlow 的新手。我遵循了一些教程并制定了我的第一个多类分类模型。

我不确定我的层是否合理设计,反正测试中的准确率是 0.98 左右。

问题是我无法使用我的模型来预测新输入。这是我的代码和用于训练模型的数据。

数据有 10 列,最后一列是类名。该模型是使用一行 9 个值来预测该行适合哪个类。

所有代码都在 colab 中运行。

!pip install sklearn
import pandas as pd
import numpy as np

import tensorflow as tf

from tensorflow import feature_column
from tensorflow.keras import layers
from tensorflow.keras import Sequential
from sklearn.model_selection import train_test_split

index_col = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'r']
dataframe = pd.read_csv('drive/MyDrive/Book2.csv', names=index_col)

train, test = train_test_split(dataframe, test_size=0.2)
train, val = train_test_split(train, test_size=0.2)

train_labels = train.filter('r')
train = train.drop('r', axis=1)

test_labels = test.filter('r')
test = test.drop('r', axis=1)

model = tf.keras.Sequential([
    tf.keras.layers.Dense(1),
    tf.keras.layers.Dense(100, activation='relu'),
    tf.keras.layers.Dense(4)
])

model.compile(optimizer='adam',
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
    metrics=['accuracy'])

model.fit(train, train_labels, epochs=20)

test_loss, test_acc = model.evaluate(test,  test_labels, verbose=2)

result = model.predict(pd.DataFrame([1, 3, 0, 3, 3, 1, 2, 3, 2]))

这是我得到的控制台错误。

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-29-942b3f127f67> in <module>()
----> 1 result = model.predict([1, 3, 0, 3, 3, 1, 2, 3, 2])

9 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in wrapper(*args, **kwargs)
    984           except Exception as e:  # pylint:disable=broad-except
    985             if hasattr(e, "ag_error_metadata"):
--> 986               raise e.ag_error_metadata.to_exception(e)
    987             else:
    988               raise

ValueError: in user code:

    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1569 predict_function  *
        return step_function(self, iterator)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1559 step_function  **
        outputs = model.distribute_strategy.run(run_step, args=(data,))
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:1285 run
        return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:2833 call_for_each_replica
        return self._call_for_each_replica(fn, args, kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/distribute/distribute_lib.py:3608 _call_for_each_replica
        return fn(*args, **kwargs)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1552 run_step  **
        outputs = model.predict_step(data)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/training.py:1525 predict_step
        return self(x, training=False)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/base_layer.py:1013 __call__
        input_spec.assert_input_compatibility(self.input_spec, inputs, self.name)
    /usr/local/lib/python3.7/dist-packages/tensorflow/python/keras/engine/input_spec.py:255 assert_input_compatibility
        ' but received input with shape ' + display_shape(x.shape))

    ValueError: Input 0 of layer sequential_2 is incompatible with the layer: expected axis -1 of input shape to have value 9 but received input with shape (None, 1)

Book2.csv 在这里

卡维

您传递给的数据框predict具有 shape (9,1)它的形状应该像你通过的训练数据集的形状(第一维除外)。

只需转置您的数据即可将形状从 更改(9,1)(1,9)

result = model.predict(pd.DataFrame([1, 3, 0, 3, 3, 1, 2, 3, 2]).T)

PS:(9,1)表示 9 个样本,每个样本有 1 个与您的模型期望不兼容的特征。(1,9)意味着 1 个样本具有 9 个特征。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何从Keras中保存的模型进行预测?

使用ImageDataGenerator训练的Keras模型进行预测的正确方法

在对keras(Multiclass)训练模型后进行预测吗?

加载预训练的 Keras 模型并进行预测

使用keras模型中的张量流图进行预测

如何在使用自定义损失函数在 Python 中训练的 DL4J 中加载 Keras 模型文件

在 keras 中实现 MLP 模型进行时间序列预测,但该模型训练效果不佳

在 tensorflow.keras 中使用训练模型进行预测时出现形状错误

使用带有 PyGAD 的遗传算法训练的 Keras 模型进行预测

使用经过训练的 Keras 模型对新的 csv 数据进行预测

如何在Keras中加快具有自定义损失功能的模型的训练?

如何使用keras从OpenCV的VideoCapture预测预训练模型?

使用未经训练的 Keras 模型预测数据

Keras 模型不会正确使用预测

如何提前停止在Keras进行模型训练?

Keras-如何使用KerasRegressor进行预测?

Keras-如何使用argmax进行预测

使用经过训练的模型进行预测

我不完全明白我将如何使用 keras 预测自定义数据

使用统计模型进行预测

使用TensorFlow模型进行预测

解包模型后如何使用 Keras 模型预测输出

使用 Keras 使用 LSTM 进行预测

来自复杂模型的自定义预测(功能性API Keras)

导出自定义 Keras 模型以用于 Cloud ML Engine 的预测

如何使用TensorBoard可视化具有自定义模型子类的keras模型?

如何对Keras文本分类进行预测?

使用keras进行预测时出错

使用Keras进行视频预测(时间序列)