我试图通过添加一些单词的随机交换来扩充imdb电影评论数据集。与图像数据不同,我不认为这个函数最初在tensorflow中。例如,对于图像,您可以执行以下操作
def transform(image, label):
image = tf.image.flip_left_right(image)
return image, label
使用tensorflow的本机函数翻转图像。但是对于增强文本,我在tf.string中看不到任何可以做到这一点的东西。因此,我正在使用textaugment中的Easy数据扩充实现https://github.com/dsfsi/textaugment
例如:
try:
import textaugment
except ModuleNotFoundError:
!pip install textaugment
import textaugment
from textaugment import EDA
import nltk
nltk.download('stopwords')
t = EDA()
t.random_swap("John is going to town")
返回“约翰进城是”
但是现在,当我尝试使用这个random_swap命令来扩充整个imdb reviews数据集时,它遇到了一个错误,因为它试图作用于张量
例如:
try:
import textaugment
except ModuleNotFoundError:
!pip install textaugment
import textaugment
import pandas as pd
import tensorflow as tf
from tensorflow.keras.preprocessing import sequence
from tensorflow.keras.models import Sequential
from tensorflow.keras.datasets import imdb
# set parameters:
max_features = 5000
maxlen = 400
batch_size = 32
embedding_dims = 50
filters = 250
kernel_size = 3
hidden_dims = 250
epochs = 1
runs = 1
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=max_features)
print(len(x_train), 'train sequences')
print(len(x_test), 'test sequences')
print('Pad sequences (samples x time)')
x_train = sequence.pad_sequences(x_train, maxlen=maxlen)
x_test = sequence.pad_sequences(x_test, maxlen=maxlen)
print('x_train shape:', x_train.shape)
print('x_test shape:', x_test.shape)
from textaugment import EDA
import nltk
nltk.download('stopwords')
t = EDA()
for text in x_train:
text = t.random_swap(text)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-7-7fc9edb2f37b> in <module>()
1 for text in x_train:
----> 2 text = t.random_swap(text)
1 frames
/usr/local/lib/python3.7/dist-packages/textaugment/eda.py in validate(**kwargs)
72 raise TypeError("p must be a fraction between 0 and 1")
73 if 'sentence' in kwargs:
---> 74 if not isinstance(kwargs['sentence'].strip(), str) or len(kwargs['sentence'].strip()) == 0:
75 raise TypeError("sentence must be a valid sentence")
76 if 'n' in kwargs:
AttributeError: 'numpy.ndarray' object has no attribute 'strip'
那么,在TensorFlow中,当本机命令不存在并且您希望创建一个自定义函数来进行扩充时,如何扩充数据呢
通过使用
imdb.load_data()
加载数据集,您不会得到文本形式的电影评论。它已经被预处理过了:评论(单词序列)已经变成了整数序列,其中每个整数代表字典中的一个特定单词因此,您不能对其应用
t.random_swap(text)
。你必须先把这些评论解码回英语单词因此,您需要相应的
word_index
。这是一个字典映射 将单词转换为整数索引在下一步中,您应该将其反转,以获得将整数索引映射到单词的字典。请注意,索引偏移了3,因为0、1和2是保留索引,用于填充序列的开头,并且未知。你可以find more details here
你应该在将
sequence.pad_sequences()
应用于评论之前对评论进行解码。否则,评论中会有很多用零表示的未知单词对于
print(x_train[0])
,您将获得:让我们解读一下这篇评论:
您将得到:
将评论解码回文本后,您可以使用
t.random_swap(decoded_review)
对其进行扩充。扩充后的数据可以用word_index
字典编码回整数序列相关问题 更多 >
编程相关推荐