CS224-learn(1)
CS224-learn(1)
记录一下自己做CS224作业的过程和一些细节
顺带一提这种作业形式真挺先进的,老师为你提供大部分内容,你只需要填入关键内容,一定程度上可能会让你偷点懒吧,但是能节省大部分的时间,而且能使作业的要求十分明确,不至于学生不知所云
Import
1 | import sys |
Read_corpus
1 | def read_corpus(category="crude"): |
这里 retuers.fileids(category) 会返回一个列表,其中每一个元素使一个字符串,字符串的值是Reuter 数据集中某个字符串的ID,类似于‘test/12345’
retuers.words(f)用于返回对应的ID的所有单词,注意python中列表推导式的运用
Distinct_words
1 | def distinct_words(corpus): |
test
1 | test_corpus = ["{} All that glitters isn't gold {}".format(START_TOKEN, END_TOKEN).split(" "), "{} All's well that ends well {}".format(START_TOKEN, END_TOKEN).split(" ")] |
Compute_co_occurrence_matrix
这里要求以窗口大小为4实现共现矩阵的构建
1 | def compute_co_occurrence_matrix(corpus, window_size=4): |
构建一个映射到共现矩阵的字典,再一句话一句话的搜索
test
1 | test_corpus = ["{} All that glitters isn't gold {}".format(START_TOKEN, END_TOKEN).split(" "), "{} All's well that ends well {}".format(START_TOKEN, END_TOKEN).split(" ")] |
Reduce_to_k_dim
构造一个共现矩阵会遇到维度太高的问题,使用SVD方法来截断奇异值,使词向量在保持良好特性的同时降低维度
1 | def reduce_to_k_dim(M, k=2): |
- TruncatedSVD(n_components= k)
功能: 这是scikit-learn库中的一个类,用于执行截断奇异值分解(Truncated Singular Value Decomposition, SVD),通常用于降维。
参数: n_components: 指定要保留的奇异值数量(即降维后的维度数)。在这个例子中,k表示目标维度。
返回值: 返回一个TruncatedSVD对象,该对象包含降维所需的信息(如奇异值、右奇异向量等)。
- svd.fit(M)
功能: 使用矩阵M来拟合TruncatedSVD模型,计算奇异值分解所需的参数。
参数: M: 输入矩阵,形状为(n_samples, n_features)。在这里,M是一个共现矩阵,表示单词之间的共现关系。
返回值: 无返回值(None),但会更新svd对象内部的状态,例如保存奇异值和右奇异向量。
- svd.transform(M)
功能: 将输入矩阵M投影到由fit方法计算出的低维空间中。
参数: M: 输入矩阵,与fit方法中的矩阵相同或具有相同的特征空间。
返回值: 返回一个形状为(n_samples, k)的降维矩阵M_reduced,其中k是由n_components指定的目标维度。这个矩阵表示原始数据在低维空间中的表示。
test
1 | test_corpus = ["{} All that glitters isn't gold {}".format(START_TOKEN, END_TOKEN).split(" "), "{} All's well that ends well {}".format(START_TOKEN, END_TOKEN).split(" ")] |
GLoVe
1 | def load_embedding_model(): |
Get_GloVe_matrix and reduce to k-dimension
1 | def get_matrix_of_vectors(wv_from_bin, required_words=['barrels', 'bpd', 'ecuador', 'energy', 'industry', 'kuwait', 'oil', 'output', 'petroleum', 'iraq']): |
Similarity and thinking
1 | w1 = wv_from_bin['good'] |