skipgram的原理及公式推倒就不详细说了,主要记录一下第一个正向传播和反向传播都自己写的神经网络,也终于体验了一把负采样对于词向量训练速度的惊人提升,感人!虽然最终的时间复杂度依然较高,不过我正在研究同样使用python的gensim为啥这么快的原因!
(明天有时间会把)数据和代码放在本人的github里,写的比较搓,待改进...
1.工具介绍
python: 3.6
电脑:mac本地跑
数据集: text8的英文语料
2. 数据预处理
- 替换文本中特殊符号
- 将文本分词
- 去除文本中的低频词
def preprocess(text, freq=5):
'''
对文本进行预处理
参数
---
text: 文本数据
freq: 词频阈值
'''
# 替换文本中特殊符号
text = text.lower()
text = text.replace('.', ' <PERIOD> ')
text = text.replace(',', ' <COMMA> ')
text = text.replace('"', ' <QUOTATION_MARK> ')
text = text.replace(';', ' <SEMICOLON> ')
text = text.replace('!', ' <EXCLAMATION_MARK> ')
text = text.replace('?', ' <QUESTION_MARK> ')
text = text.replace('(', ' <LEFT_PAREN> ')
text = text.replace(')', ' <RIGHT_PAREN> ')
text = text.replace('--', ' <HYPHENS> ')
text = text.replace('?', ' <QUESTION_MARK> ')
text = text.replace(':', ' <COLON> ')
words = text.split()
# 删除低频词,减少噪音影响
word_counts = Counter(words)
trimmed_words = [word for word in words if word_counts[word] > freq]
return trimmed_words
3. 训练样本构建
- 获取vocabulary,即id->word,和word->id这两个单词映射表。
- 将文本序列转化为id序列。
- 剔除停用词:停用词可能频率比较高,采用以下公式来计算每个单词被删除的概率大小。
其中