【发布时间】:2020-07-31 16:30:42
【问题描述】:
我正在使用 Keras Tensorflow 进行 NLP,我目前正在处理 imdb 评论数据集。我想使用 hub.KerasLayer。我想直接传递实际的 x 和 y 值。因此,在我的 model.fit 语句中,句子为 x,标签为 y。我的代码:
import csv
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
import tensorflow_hub as hub
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
imdb, info = tfds.load("imdb_reviews", with_info=True, as_supervised=True)
imdb_train=imdb['train']
imdb_test=imdb['test']
training_sentences=[]
training_labels=[]
test_sentences=[]
test_labels=[]
for a,b in imdb_train:
training_sentences.append(a.numpy().decode("utf8"))
training_labels.append(b.numpy())
for a,b in imdb_test:
test_sentences.append(a.numpy().decode("utf8"))
test_labels.append(b.numpy())
model = "https://tfhub.dev/google/tf2-preview/gnews-swivel-20dim/1"
hub_layer = hub.KerasLayer(model, output_shape=[20], input_shape=[],
dtype=tf.string, trainable=True)
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(1))
model.compile(loss=tf.keras.losses.BinaryCrossentropy(from_logits=True),optimizer='adam', metrics=[tf.metrics.BinaryAccuracy(threshold=0.0, name='accuracy')])
尝试
history = model.fit(x=training_sentences,
y=training_labels,
validation_data=(test_sentences, test_labels),
epochs=2)
不起作用,因为 training_labels 的形状/格式不正确。我现在的方法是再次使用标记器,因为然后我会以正确的格式/形状获得结果(来自 texts_to_sequences)。为此,我必须首先将其转换为是/否(或 a/b 等)字符串。
training_labels_test=[]
for i in training_labels:
if i==0: training_labels_test.append("no")
if i==1: training_labels_test.append("yes")
testtokenizer=Tokenizer()
testtokenizer.fit_on_texts(training_labels_test)
test_labels_pad=testtokenizer.texts_to_sequences(training_labels_test)
val_labels_test=[]
for i in test_labels:
if i==0: val_labels_test.append("no")
if i==1: val_labels_test.append("yes")
testtokenizer.fit_on_texts(val_labels_test)
val_labels_pad=testtokenizer.texts_to_sequences(val_labels_test)
因为我现在有 1 和 2 作为标签,所以我需要更新我的模型:
model = tf.keras.Sequential()
model.add(hub_layer)
model.add(tf.keras.layers.Dense(16, activation='relu'))
model.add(tf.keras.layers.Dense(2))
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
metrics=['accuracy'])
然后我尝试适应它:
history = model.fit(x=training_sentences,
y=test_labels_pad,
validation_data=(test_sentences, val_labels_pad),
epochs=2)
问题是loss是nan,准确率计算不正确。
错在哪里?
请不要说我的问题实际上是关于这种特定方式以及为什么这个标记器不起作用。我知道还有其他可行的方法。
【问题讨论】:
标签: python tensorflow keras nlp tokenize