python - 如何在 python 中为在 tensorflow 中实现的模型创建混淆矩阵?
问题描述
我正在使用 TensorFlow 在 Python 中训练模型,但我想打印模型预测数据(预测与实际)的混淆矩阵。我怎样才能做到这一点?到目前为止,我的代码(不包括数据加载和预处理)如下:
from sklearn.preprocessing import LabelEncoder
Y = data.label
le = LabelEncoder()
Y = le.fit_transform(Y)
Y = Y.reshape(-1,1)
len(X)
sequences = list()
for line in X:
# integer encode line
encoded_seq = [char_index[char] for char in line]
# store
sequences.append(encoded_seq)
padded_inputs = tf.keras.preprocessing.sequence.pad_sequences(
sequences, padding="pre")
print(padded_inputs)
ex = tf.keras.preprocessing.sequence.pad_sequences(sequences, padding="pre")
print(ex)
#And here is the train_test_split
X_train, X_test, y_train, y_test = train_test_split(padded_inputs, Y, test_size= 0.1,
random_state = 0)
X_train
y_train = y_train.astype("int32")
y_train
X_train.shape
X_test
print(X_train.shape)
max_len = 19
max_words = 57
from tensorflow.keras.optimizers import RMSprop
def RNN():
inputs = tf.keras.Input(name='inputs',shape=[max_len])
layer = Embedding(max_words,19,input_length=max_len)(inputs)
layer = LSTM(64)(layer)
layer = Dense(256,name='FC1')(layer)
layer = Activation('relu')(layer)
layer = Dropout(0.5)(layer)
layer = Dense(1,name='out_layer')(layer)
layer = Activation('sigmoid')(layer)
model = tf.keras.Model(inputs=inputs,outputs=layer)
return model
model = RNN()
model.summary()
model.compile(loss='binary_crossentropy',optimizer=RMSprop(),metrics=['accuracy'])
num_epochs = 40
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
history=model.fit(X_train, y_train,batch_size=128, epochs= num_epochs, validation_split=0.2,
callbacks=[tensorboard_callback], verbose=2)
accr = model.evaluate(X_test,y_test)
print('Test set\nLoss: {:0.3f}\nAccuracy: {:0.3f}'.format(accr[0],accr[1]))
yhat = model.predict(X_test)
我试过使用:tf.math.confusion_matrix(labels, predictions, num_classes=None, weights=None, dtype=tf.dtypes.int32,name=None,但我不知道如何正确使用它代码。
解决方案
推荐阅读
- android - 片段在活动上重叠:Android Studio
- mongodb - 如何使用 golang 和 mongodb 过滤日期?
- python - 在 Django REST 框架中使用分组序列化 M-2-M 关系
- javascript - Web Share API 在 iOS Safari 中只能运行一次
- r - 删除包含相同条目不同两列的行
- python - 在 python 中运行时如何逐行记录代码
- python - 在Python / Numpy中获取满足条件列表的数组元素数
- swift - 警告“'init()' 已弃用”。【Swift、Ios app、学习模型】
- c++ - 链接器生成的列表(可能是高度非标准的)C++。可能的?
- apache-spark - 使用 mapGroupsWithState 进行状态处理 - 多次输出相同的键