关键词:
- word embedding
- cnn
- glove:大神预先做好的词向量(就是每个单词用固定维数的向量表示)
- 20_newsgroup:需要进行分类的文本(training data and testing data)
过程
- 将所有的新闻样本转化为词索引序列
- 生成一个glove词向量矩阵
- 将词向量矩阵载入Keras Embedding层,设置该层的权重不可再训练
- Keras Embedding层之后连接一个1D的卷积层,并用一个softmax全连接输出新闻类别
原理分析
Get training data and testing data
texts = [] # texts表示的是一系列文件文字集(X)
labels_index = {} # 这个字典用于讲文件夹名(新闻类别)和label_id对应起来
labels = [] # labels表示每个text所属类别(y)
TEXT_DATA_DIR = "text_data/20_newsgroup"
for name in sorted(os.listdir(TEXT_DATA_DIR)):
path = os.path.join(TEXT_DATA_DIR, name)
print('\n遍历文件夹 %s :' % name)
if os.path.isdir(path):
labels_id = len(labels_index)
labels_index[name] = labels_id
for fname in sorted(os.listdir(path)):
if fname.isdigit():
print("%s \t" % fname, end="")
fpath = os.path.join(path, fname)
f = open(fpath, encoding='latin1')
texts.append(f.read())
f.close()
labels.append(labels_id)
# 得到的每个text表示的是一个文件里的所有内容,而不是指单独一个单词
print('Found %s texts.' % len(texts))
>>> Found 19997 texts.
每个text
包含个数不等的word
,并且有对应的新闻类别(labels_id)
,labels_index
就是连接这个两个关系的字典
keras.preprocessing.text.textTokenizer
文本预处理
MAX_NUM_WORDS = 6000
tokenizer = Tokenizer(num_words=MAX_NUM_WORDS)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
# 字典,key = sequences of text, values = labels_id
word_index = tokenizer.word_index
print('Found %s unique tokens.' % len(texts))
print('Found %s words.' % len(word_index))
MAX_SEQUENCE_LENGTH = 500 # 每个text中取多少word, (多剪少补)
data = pad_sequences(sequences, maxlen=MAX_SEQUENCE_LENGTH)
labels = to_categorical(np.array(labels))
print('Shape of data tensor:', data.shape)
print('Shape of label tensor:', labels.shape)
Tokenizer类讲每个text变成一个sequence,每个word对应sequence中的元素。
将有序数据随机化用于训练和验证:比例(8:2)
VALIDATION_SPLIT = 0.2
indices = np.arange(data.shape[0])
np.random.shuffle(indices)
data = data[indices]
labels = labels[indices]
nb_validation_samples = int(VALIDATION_SPLIT * data.shape[0])
x_train = data[:-nb_validation_samples]
y_train = labels[:-nb_validation_samples]
x_val = data[-nb_validation_samples:]
y_val = labels[-nb_validation_samples:]
获取Glove词向量
# glove字典,每个单词对应一个100维的向量
def get_glove_dict(glove_dir):
embeddings_index = {}
f = open(os.path.join(glove_dir, 'glove.6B.100d.txt'))
for line in f:
values = line.split()
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()
print('Found %s word vectors.' % len(embeddings_index))
return embeddings_index
输出:
>>> Found 400000 word vectors.
词向量嵌入Embedding
GLOVE_DIR = 'text_data/glove.6B'
EMBEDDING_DIM = 100
embedding_matrix = np.zeros((len(word_index) + 1, EMBEDDING_DIM))
embedding_index = get_glove_dict(GLOVE_DIR)
for word, i in word_index.items():
embedding_vector = embedding_index.get(word)
if embedding_vector is not None:
# words not found in embedding index will be all-zeros.
embedding_matrix[i] = embedding_vector
embedding_layer = Embedding(len(word_index) + 1,
EMBEDDING_DIM,
weights=[embedding_matrix],
input_length=MAX_SEQUENCE_LENGTH,
trainable=False)
分析:
这里我们获取到一个400000x100
的词向量,看来英语单词大概有400000个。
training_data是19997x500
,每个元素表示一个word,我们需要为每个word再词向量中找到它对应的向量,这就是word embedding需要做的工作,可以节省大量计算时间。
embedding_vector = embedding_index.get(word)
就是获取traing_data中出现的word的vector
输入卷积层
sequence_input = Input(shape=(MAX_SEQUENCE_LENGTH,), dtype='int32')
embedded_sequences = embedding_layer(sequence_input)
x = Conv1D(128, 5, activation='relu')(embedded_sequences)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(5)(x)
x = Conv1D(128, 5, activation='relu')(x)
x = MaxPooling1D(15)(x) # global max pooling
x = Flatten()(x)
x = Dense(128, activation='relu')(x)
preds = Dense(len(labels_index), activation='softmax')(x)
model = Model(sequence_input, preds)
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',
metrics=['acc'])
# happy learning!
model.fit(x_train, y_train, validation_data=(x_val, y_val),
epochs=5, batch_size=128)
Result:
loss: 0.1446 - acc: 0.9448 - val_loss: 0.1871 - val_acc: 0.9325
还是不错的
参考:
https://github.com/MoyanZitto/keras-cn/blob/master/docs/legacy/blog/word_embedding.md