为什么我在训练Tensorflow Keras模型时输出奇怪的损失和准确率值?

我在Tensorflow中使用Python训练了一个自定义文本分类器,用于将句子分类为问题/包含信息的句子,使用的代码如下:

import tensorflow as tffrom tensorflow import kerasfrom tensorflow.keras.preprocessing.text import Tokenizerfrom tensorflow.keras.preprocessing.sequence import pad_sequencestext = ""with open("/content/train_new.txt") as source:  for line in source.readlines():    text = text + lineprint("text: " + text)sentences = []labels = []for item in text.split("<n>"):  parts = item.split("<t>")  print(parts)  sentences.append(parts[0])  labels.append(parts[1])print(sentences)print(labels)print("----")train_test_split_percentage = 80training_size = round((len(sentences)/100)*train_test_split_percentage)print("training size: " + str(training_size) + " of " + str(len(labels)))training_sentences = sentences[0:training_size]testing_sentences = sentences[training_size:]training_labels = labels[0:training_size]testing_labels = labels[training_size:]vocab_size = 100max_length = 10tokenizer = Tokenizer(num_words = vocab_size, oov_token="<OOV>")tokenizer.fit_on_texts(sentences)word_index = tokenizer.word_indextraining_sequences = tokenizer.texts_to_sequences(training_sentences)training_padded = pad_sequences(training_sequences, maxlen=max_length, padding="post", truncating="post")testing_sequences = tokenizer.texts_to_sequences(testing_sentences)testing_padded = pad_sequences(testing_sequences, maxlen=max_length, padding="post", truncating="post")# convert training & testing data into numpy array# Need this block to get it to work with TensorFlow 2.ximport numpy as nptraining_padded = np.array(training_padded)training_labels = np.asarray(training_labels).astype('float32').reshape((-1,1))testing_padded = np.array(testing_padded)testing_labels = np.asarray(testing_labels).astype('float32').reshape((-1,1))# defining the modelmodel = tf.keras.Sequential([    tf.keras.layers.Embedding(vocab_size, 24, input_length=max_length),    tf.keras.layers.GlobalAveragePooling1D(),    tf.keras.layers.Dense(24, activation='relu'),    tf.keras.layers.Dense(1, activation='softmax')])model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])# training the modelnum_epochs = 1000history = model.fit(training_padded, training_labels, epochs=num_epochs, validation_data=(testing_padded, testing_labels), verbose=2)

然而,在训练过程中,它输出了奇怪的准确率和损失值,如下所示:

Epoch 972/10009/9 - 0s - loss: -8.2316e+03 - accuracy: 0.7345 - val_loss: -2.7299e+04 - val_accuracy: 0.0000e+00Epoch 973/10009/9 - 0s - loss: -8.2452e+03 - accuracy: 0.7345 - val_loss: -2.7351e+04 - val_accuracy: 0.0000e+00Epoch 974/10009/9 - 0s - loss: -8.2571e+03 - accuracy: 0.7345 - val_loss: -2.7363e+04 - val_accuracy: 0.0000e+00Epoch 975/10009/9 - 0s - loss: -8.2703e+03 - accuracy: 0.7345 - val_loss: -2.7416e+04 - val_accuracy: 0.0000e+00

train_new.txt文件中的数据格式为text<t>class_num<n>

当尝试使用model.predict()函数进行预测时,它总是输出[[1.]]

我的代码有什么问题?


回答:

tf.keras.layers.Dense(1, activation='sigmoid')

如果你在进行二分类任务,你应该使用sigmoid作为激活函数。然而,

tf.keras.layers.Dense(2, activation='softmax') 

在概率术语上也是正确的。

Softmax输出的总和总是等于一。这就是为什么你每次都得到1作为输出。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注