本次作业主要介绍
- 余弦相似性
- 两种求词向量的方法
- 基于计数(词共现矩阵 + SVD)
- 基于预测(word2vec)
完整代码:CS 224N | Home
一、环境及数据问题
1.gensim安装
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple gensim
2.reuters数据集读取
直接运行上面的代码会报错,解决方案如下:
直接下载数据
链接: https://pan.baidu.com/s/1zo87Uq7_dKbu773ZT_cwTw 提取码: 9jni
在打开Jupyter Notebook的路径下新建文件夹 nltk_data 在nltk_data文件夹下将reuters放进去
然后运行,就不会报错了,撒花🎉~
3.加载数据集‘word2vec-google-news-300’又又又报错了
解决方案:
4.由于gensim版本问题,导致几处代码跑不通,本环境版本。
此处跑不通
解决方案参考: Migrating from Gensim 3.x to 4 · RaRe-Technologies/gensim Wiki · GitHub
经过10086次操作之后,第一次作业的代码可以完美复现啦,啦啦啦~
二、内容理解
1.导入包
# All Import Statements Defined Here
# Note: Do not add to this list.
# All the dependencies you need, can be installed by running .
# ----------------
import sys
assert sys.version_info[0]==3
assert sys.version_info[1] >= 5
from gensim.models import KeyedVectors
from gensim.test.utils import datapath
import pprint
import matplotlib.pyplot as plt
plt.rcParams['figure.figsize'] = [10, 5]
# import nltk
# nltk.download('reuters')
from nltk.corpus import reuters
import numpy as np
import random
import scipy as sp
from sklearn.decomposition import TruncatedSVD
from sklearn.decomposition import PCA
START_TOKEN = '<START>'
END_TOKEN = '<END>'
np.random.seed(0)
random.seed(0)
# ----------------
2.Part 1 Count-Based Word Vectors (10 points)
思路框架:
- 对于语录料库中的文档单词, 得先构建一个词典(唯一单词且排好序)
- 然后我们就是基于词典和语料库,为每个单词构建词向量, 也就是共现矩阵
- 对共现矩阵降维,就得到了最终的词向量
- 可视化
2.1 构建词典(基于语料库)
2.1.1 共现矩阵定义
2.1.2 遍历每一篇文档,获得所有的单词, 去重排序, 记录单词总数。
def read_corpus(category="crude"):
""" Read files from the specified Reuter's category.
Params:
category (string): category name
Return:
list of lists, with words from each of the processed files
"""
files = reuters.fileids(category)
return [[START_TOKEN] + [w.lower() for w in list(reuters.words(f))] + [END_TOKEN] for f in files]
reuters_corpus = read_corpus()
pprint.pprint(reuters_corpus[:3], compact=True, width=100)
读取578篇语料
加载每一篇文章中的单词 且全部变成小写字母
在每一篇文章的开头和结尾分别加[START_TOKEN和 END_TOKEN
计算出语料库中的不同单词,然后排序
#21计算出语料库中的不同单词 然后排序
def distinct_words(corpus):
""" Determine a list of distinct words for the corpus.
Params:
corpus (list of list of strings): corpus of documents
Return:
corpus_words (list of strings): list of distinct words across the corpus, sorted (using python 'sorted' function)
num_corpus_words (integer): number of distinct words