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



我是一个完全陌生的TensorFlow。我遵循了一些教程并建立了我的第一个多类分类模型。

我不确定我的图层设计是否合理,无论如何,测试的准确性是0.98左右。

问题是我不能用我的模型来预测一个新的输入。以下是我用来训练模型的代码和数据。

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

所有代码都是协同运行的。

!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的数据帧形状为(9,1)。它的形状应该像你已经通过的火车数据集的形状(除了第一维)。

简单地将数据从(9,1)转换为(1,9):

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

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

相关内容

  • 没有找到相关文章

最新更新