【发布时间】:2021-05-20 13:16:00
【问题描述】:
我是 tensorflow2/keras 的新手。我在 tensorflow 网站上关注了这个tutorial。我没有将文本数据下载到目录,而是使用tensorflow_datasets 将 imdb 数据集直接加载到张量/numpy 数组中。下面是我的代码。
import os
import re
import string
import pandas as pd
import numpy as np
import tensorflow as tf
import tensorflow_hub as hub
import tensorflow_datasets as tfds
import matplotlib.pyplot as plt
from tensorflow.keras import layers
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
print("Version: ", tf.__version__)
print("Eager mode: ", tf.executing_eagerly())
print("Hub version: ", hub.__version__)
print("GPU is", "available" if tf.config.list_physical_devices('GPU') else "NOT AVAILABLE")
train_data, test_data = tfds.load(name="imdb_reviews", split=["train", "test"],
batch_size=-1, as_supervised=True)
X_train, y_train = tfds.as_numpy(train_data)
X_test, y_test = tfds.as_numpy(test_data)
# process text
def custom_standardization(input_data):
lowercase = tf.strings.lower(input_data)
stripped_html = tf.strings.regex_replace(lowercase, '<br />', ' ')
return tf.strings.regex_replace(stripped_html,
'[%s]' % re.escape(string.punctuation),
'')
max_features = 1000
sequence_length = 50
vectorize_layer = TextVectorization(
standardize=custom_standardization,
max_tokens=max_features,
output_mode='int',
output_sequence_length=sequence_length)
# Make a text-only dataset (without labels), then call adapt
vectorize_layer.adapt(X_train)
def vectorize_text(text):
text = tf.expand_dims(text, -1)
return vectorize_layer(text)
#check data
first_review, first_label = X_train[0], y_train[0]
print("Review", first_review)
print("Vectorized review", vectorize_text(first_review))
print("11 ---> ",vectorize_layer.get_vocabulary()[11])
print(" 44 ---> ",vectorize_layer.get_vocabulary()[44])
print('Vocabulary size: {}'.format(len(vectorize_layer.get_vocabulary())))
# vectorize both train and test text data
X_train = vectorize_text(X_train)
X_test = vectorize_text(X_test)
embedding_dim = 16
#define and compile model
model = tf.keras.Sequential([
layers.Embedding(max_features + 1, embedding_dim),
layers.GlobalAveragePooling1D(),
layers.Dropout(0.2),
layers.Dense(256, activation='relu'),
layers.Dropout(0.2),
layers.Dense(1)])
model.summary()
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# fit the model
history = model.fit(X_train, y_train, epochs=5, batch_size=32, verbose=2, validation_data=(X_test, y_test))
我得到的输出如下:
_________________________________________________________________
Epoch 1/5
782/782 - 4s - loss: 0.0000e+00 - accuracy: 0.5000 - val_loss: 0.0000e+00 - val_accuracy: 0.5000
Epoch 2/5
782/782 - 4s - loss: 0.0000e+00 - accuracy: 0.5000 - val_loss: 0.0000e+00 - val_accuracy: 0.5000
Epoch 3/5
782/782 - 4s - loss: 0.0000e+00 - accuracy: 0.5000 - val_loss: 0.0000e+00 - val_accuracy: 0.5000
Epoch 4/5
782/782 - 4s - loss: 0.0000e+00 - accuracy: 0.5000 - val_loss: 0.0000e+00 - val_accuracy: 0.5000
Epoch 5/5
782/782 - 4s - loss: 0.0000e+00 - accuracy: 0.5000 - val_loss: 0.0000e+00 - val_accuracy: 0.5000
准确率都是 50%!有些不对劲。我很困惑为什么会这样?我按照教程,从头开始训练嵌入层。花了几个小时试图找出原因。 有谁知道为什么出错了?谢谢!
【问题讨论】:
-
准确率始终为 50%,因为您的网络每次使用带有 1 个神经元的
softmax时都会输出 1。 -
感谢您的帮助。我删除了
activation='softmax'它仍然输出相同的结果! -
我编辑了我的问题。
标签: python tensorflow keras tensorflow2.0 tf.keras