Я кодировал модель анализа настроений с тенорным потоком кер. Я использую набор данных csv, который имеет метки (pos: 1, neg: 0) в строке 1 и тексты Engli sh в строке 2. Я ожидаю, что при вводе некоторых текстов через текстовый файл будет показано число от 0 до 1 , Однако, несмотря на то, что я установил модель, коэффициент потерь остается отрицательным, а коэффициент точности не увеличивается, включая показатели проверки. Я не знаю, в чем дело. Таким образом, я приложил свои коды. Большое спасибо.
import csv
import tensorflow as tf
import numpy as np
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
vocab_size = 20000
embedding_dim = 16
max_length = 120
trunc_type='post'
padding_type='post'
oov_tok = "<OOV>"
training_portion = .8
sentences = []
labels = []
stopwords = [ "a", "about", "above", "after", "again", "against", "all", "am", "an", "any", "are",
"as", "at", "be", "because", "been", "before", "being", "below", "between", "both", "but", "by",
"could", "did", "do", "does", "doing", "down", "during", "each", "few", "for", "from", "further",
"had", "has", "have", "having", "he", "he'd", "he'll", "he's", "her", "here", "here's", "hers",
"herself", "him", "himself", "his", "how", "how's", "i", "i'd", "i'll", "i'm", "i've", "if", "in",
"into", "is", "it", "it's", "its", "itself", "let's", "me", "more", "most", "my", "myself", "nor",
"of", "on", "once", "only", "or", "other", "ought", "our", "ours", "ourselves", "out", "over", "own",
"same", "she", "she'd", "she'll", "she's", "should", "so", "some", "such", "than", "that", "that's",
"the", "their", "theirs", "them", "themselves", "then", "there", "there's", "these", "they",
"they'd", "they'll", "they're", "they've", "this", "those", "through", "to", "too", "under", "until",
"up", "very", "was", "we", "we'd", "we'll", "we're", "we've", "were", "what", "what's", "when",
"when's", "where", "where's", "which", "while", "who", "who's", "whom", "why", "why's", "with",
"would", "you", "you'd", "you'll", "you're", "you've", "your", "yours", "yourself", "yourselves" ]
print(len(stopwords)
with open("/train.csv", 'r', encoding='latin1') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
next(reader)
for row in reader:
labels.append(row[0])
sentence = row[1]
for word in stopwords:
token = " " + word + " "
sentence = sentence.replace(token, " ")
sentences.append(sentence)
train_size = int(len(sentences) * training_portion)
train_sentences = sentences[:train_size]
train_labels = labels[:train_size]
validation_sentences = sentences[train_size:]
validation_labels = labels[train_size:]
tokenizer = Tokenizer(num_words = vocab_size, oov_token=oov_tok)
tokenizer.fit_on_texts(train_sentences)
word_index = tokenizer.word_index
train_sequences = tokenizer.texts_to_sequences(train_sentences)
train_padded = pad_sequences(train_sequences, padding=padding_type, maxlen=max_length)
validation_sequences = tokenizer.texts_to_sequences(validation_sentences)
validation_padded = pad_sequences(validation_sequences, padding=padding_type, maxlen=max_length)
label_tokenizer = Tokenizer()
label_tokenizer.fit_on_texts(labels)
training_label_seq = np.array(label_tokenizer.texts_to_sequences(train_labels))
validation_label_seq = np.array(label_tokenizer.texts_to_sequences(validation_labels))
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, 64),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(128, return_sequences=True)),
tf.keras.layers.Bidirectional(tf.keras.layers.LSTM(32)),
tf.keras.layers.Dense(64, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(16, activation='relu'),
tf.keras.layers.Dropout(0.5),
tf.keras.layers.Dense(1)
])
model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),
optimizer=tf.keras.optimizers.Adam(1e-4),
metrics=['accuracy'])
model.summary()
history = model.fit(train_padded, training_label_seq, epochs=6,
validation_data=(validation_padded, validation_label_seq),
validation_steps=30)
введите описание изображения здесь