训练后如何使用 keras NN 对数据进行分类?

数据挖掘 Python 神经网络 分类 喀拉斯 张量流
2021-09-29 01:47:42

我已经定义、训练并保存了我的张量 keras NN。既然已经完成了,我如何使用它将分类输出到非训练数据?

import tensorflow as tf
import numpy as np
from tensorflow.keras import layers
from syslog import syslog_pred

model = tf.keras.Sequential()
# Adds a densely-connected layer with 64 units to the model:
model.add(layers.Dense(128, activation='relu'))
# Add another:
model.add(layers.Dense(128, activation='relu'))
# Add a softmax layer with 8 output units:
model.add(layers.Dense(8, activation='softmax'))

model.compile(optimizer=tf.train.AdamOptimizer(0.001),
              loss='categorical_crossentropy',
              metrics=['accuracy'])

model.load_weights('.my_model')

x = np.array([arr[:-1] for arr in syslog_pred], dtype=np.float32)
dataset = tf.data.Dataset.from_tensor_slices(x)

answer = model.predict(dataset, steps=30)
print(answer)

最后的代码不是应该的,但我有点迷茫。任何帮助,将不胜感激!

2个回答

一旦你有一个训练好的模型,你可以通过使用predict模型的方法将新样本传递给它,这将为你提供所有类的概率。然后,您选择每个样本概率最高的类作为预测类:

y_prob = model.predict(new_data)   # Get class probability vector for each sample
y_class = y_prob.argmax(axis=-1)   # Set prediction to class with highest probability

如果您使用的是Sequential()模型,您也可以使用该predict_classes方法,它会得到相同的答案:

y_class = model.predict_classes(new_data)

要预测类,您只需要:

answer = model.predict_classes(dataset)