Tensorflow2.0之影评文本情感分类 (embedding + LSTM +subword--tensorflow_datasets)

%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
import sys
import time
import sklearn
import tensorflow as tf

from tensorflow import keras

print(tf.__version__)
print(sys.version_info)
for module in mpl,np,pd,sklearn,tf,keras:
    print(module.__name__,module.__version__)

 

import tensorflow_datasets as tfds
# subword-level model
dataset, info = tfds.load('imdb_reviews/subwords8k',with_info=True,as_supervised=True)
train_dataset , test_dataset = dataset['train'],dataset['test']
print(info)

# subword
tokenizer = info.features['text'].encoder
print('vocabulary size: {}'.format(tokenizer.vocab_size))

 

# word -> subword
sample_string = "Tensorflow is cool."
tokenized_string = tokenizer.encode(sample_string)
print('tokenized string is {}'.format(tokenized_string))
original_string = tokenizer.decode(tokenized_string)
print('original string is {}'.format(original_string))

for token in tokenized_string:
    print('{} --> "{}"'.format(token,tokenizer.decode([token])))

 

buffer_size = 10000
batch_size = 64

train_dataset = train_dataset.shuffle(buffer_size)
#train_dataset = train_dataset.padded_batch(batch_size,train_dataset.output_shapes)
#test_dataset = test_dataset.padded_batch(batch_szie,test_dataset.output_shapes)
train_dataset = train_dataset.padded_batch(batch_size,tf.compat.v1.data.get_output_shapes(train_dataset))
test_dataset = test_dataset.padded_batch(batch_size,tf.compat.v1.data.get_output_shapes(test_dataset))

print(tf.compat.v1.data.get_output_shapes(train_dataset))
print(tf.compat.v1.data.get_output_shapes(test_dataset))

 

# 双向 循环网络
embedding_dim = 16
batch_size = 128
varcob_size = tokenizer.vocab_size
# keras.layers.Bidirectional
# keras.layers.SimpleRNN
bidir_rnn_model = keras.models.Sequential([
    keras.layers.Embedding(varcob_size,embedding_dim),
    keras.layers.Bidirectional(keras.layers.LSTM(units=32,return_sequences=True)),
    keras.layers.Bidirectional(keras.layers.LSTM(units=32,return_sequences=False)),#因为后面是全连接层 故而 False
    keras.layers.Dense(32,activation='relu'),
    keras.layers.Dense(1,activation='sigmoid')
])

bidir_rnn_model.summary()
bidir_rnn_model.compile(loss='binary_crossentropy',optimizer='adam',metrics=['accuracy'])

 

epochs =5
history = bidir_rnn_model.fit(train_dataset,epochs=epochs,validation_data=test_dataset)

 

def plot_leraning_curves(history, label, epochs, min_value, max_value):
    data = {}
    data[label] = history.history[label]
    data['val_'+label] = history.history['val_'+label]
    pd.DataFrame(data).plot(figsize=(8, 5))
    plt.grid(True)
    plt.axis([0, epochs, min_value, max_value])
    plt.show()
    
plot_leraning_curves(history, 'accuracy', epochs, 0, 1)
plot_leraning_curves(history, 'loss', epochs, 0, 1)

 

bidir_rnn_model.evaluate(test_dataset)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是在 TensorFlow 2.0 中使用 LSTM 实现对路透社数据集的文本分类的步骤: 1. 导入所需的库 ``` import numpy as np import tensorflow as tf from tensorflow.keras.datasets import reuters from tensorflow.keras.preprocessing.sequence import pad_sequences from tensorflow.keras.utils import to_categorical from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Embedding, LSTM, Dense ``` 2. 加载路透社数据集 ``` (x_train, y_train), (x_test, y_test) = reuters.load_data(num_words=10000) ``` 其中,`num_words` 参数指定了只要用到最频繁的前 10000 个单词。 3. 对数据进行预处理 ``` maxlen = 500 # 每个样本最多保留 500 个单词 x_train = pad_sequences(x_train, maxlen=maxlen) x_test = pad_sequences(x_test, maxlen=maxlen) num_classes = np.max(y_train) + 1 y_train = to_categorical(y_train, num_classes) y_test = to_categorical(y_test, num_classes) ``` 这里使用了 `pad_sequences` 函数将每个样本都填充到长度为 500,不足的部分用 0 补齐。同时,使用 `to_categorical` 函数将标签转换为 one-hot 编码。 4. 构建模型 ``` model = Sequential() model.add(Embedding(10000, 128)) model.add(LSTM(128, dropout=0.2, recurrent_dropout=0.2)) model.add(Dense(num_classes, activation='softmax')) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) ``` 这里使用了 Embedding 层将每个单词映射为 128 维的向量,然后使用 LSTM 层进行序列建模,最后接上一个 Dense 层,输出 num_classes 个类别的概率。使用 `compile` 函数来定义损失函数、优化器和评价指标。 5. 训练模型 ``` model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test)) ``` 这里使用 `fit` 函数来训练模型,指定了每个 batch 的大小为 32,训练 5 次,并在测试集上进行验证。 6. 评估模型 ``` score, acc = model.evaluate(x_test, y_test, batch_size=32) print('Test score:', score) print('Test accuracy:', acc) ``` 这里使用 `evaluate` 函数来评估模型在测试集上的表现,输出测试集的损失和准确率。 以上就是在 TensorFlow 2.0 中使用 LSTM 实现对路透社数据集的文本分类的完整步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值