self.sim_svd = [] print("Calculating the sim_svd...") tbar = tqdm(total=len(self.word_vector)) for word in self.word_vector: if word[0] in self.vocab and word[1] in self.vocab: idx0 = self.vocab.index(word[0]) idx1 = self.vocab.index(word[1]) vector0 = self.result[idx0] vector1 = self.result[idx1] norm0 = np.linalg.norm(vector0) norm1 = np.linalg.norm(vector1) frac0 = np.dot(vector0, vector1) frac1 = norm0 * norm1 if frac1 != 0: sim = np.around(frac0 / frac1, 1) else: sim = 0 self.sim_svd.append(sim) else: self.sim_svd.append(0) tbar.update(1) tbar.close() # print(self.sim_svd) f = open('sim_svd', 'wb') pickle.dump(self.sim_svd, f) f.close()

时间: 2024-02-10 22:35:14 浏览: 21
这段代码看起来是在计算两个词语在词向量空间中的相似度,并将结果保存到了一个文件中。具体来说,代码首先创建了一个空的列表 self.sim_svd,然后通过遍历词向量列表 self.word_vector,计算每个词语与其他词语的相似度,并将结果添加到 self.sim_svd 中。计算相似度的公式使用的是余弦相似度,即两个向量的点积除以它们的模长之积。如果两个词语都在词汇表 self.vocab 中,就可以通过它们在词汇表中的索引找到它们在词向量矩阵 self.result 中对应的向量,并计算它们的点积和模长,从而得到它们的相似度;如果两个词语中有任何一个不在词汇表中,则将它们的相似度设为 0。最后,代码将计算得到的相似度列表 self.sim_svd 保存到一个名为 'sim_svd' 的二进制文件中,使用 pickle.dump() 函数实现。
相关问题

def SVG_process(self): # SVG方法 self.get_subword_vector() M = np.zeros((len(self.vocab), len(self.vocab))) df = pd.DataFrame(M, index=self.vocab, columns=self.vocab) print("Calculating the subword vector...") # 利用dataframe的字符串索引功能,使用子词向量进行计数,记录子词向量在词表中的出现频率 tbar = tqdm(total=len(self.subword_vector)) for i in self.subword_vector: try: df.at[i[0], i[1]] += 1 except: pass tbar.update(1) tbar.close() M = np.array(df) print(np.max(M)) svd = TruncatedSVD(n_components=3) self.result = svd.fit_transform(M) print(self.result.shape) def SGNS_process(self): print("Calculating the sim_sgns...") logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') self.sim_sgns = [] vec_sgns = Word2Vec(LineSentence('dataset.txt'), vector_size=100, window=2, sg=1, hs=0, min_count=1, workers=multiprocessing.cpu_count()) tbar = tqdm(total=len(self.word_vector)) for word in self.word_vector: try: self.sim_sgns.append(vec_sgns.wv.similarity(word[0], word[1])) except: self.sim_sgns.append(0) tbar.update(1) tbar.close() # print(self.sim_sgns) f = open('sim_sgns', 'wb') pickle.dump(self.sim_sgns, f) f.close()

这段代码中包含了两个方法,一个是SVG_process,另一个是SGNS_process。 SVG_process方法中,首先调用了get_subword_vector方法获取词表中的子词向量,然后使用一个二维数组M初始化一个DataFrame对象df,用于记录子词向量在词表中的出现频率。接着遍历子词向量列表,利用DataFrame的字符串索引功能将子词向量的出现次数记录在df中。最后使用TruncatedSVD对M进行奇异值分解,得到降维后的结果self.result。 SGNS_process方法中,首先使用Word2Vec读取文本数据集,构建词向量模型vec_sgns。然后遍历词向量列表,使用wv.similarity计算每个词向量之间的相似度,并将结果保存在self.sim_sgns列表中。最后将self.sim_sgns保存到文件中。

def output(self): f = open('2020522085.txt', 'w' ,encoding='utf-8') with open('sim_svd', 'rb') as f1: self.sim_svd = pickle.load(f1) f1.close() with open('sim_sgns', 'rb', encoding='utf-8') as f1: self.sim_sgns = pickle.load(f1) f1.close() for i in range(500): f.write(str(' '.join(self.word_vector[i])) + ' ' + str(self.sim_svd[i]) + ' ' + str(self.sim_sgns[i]) + '\n') f.close()

这段代码看起来是在将之前计算得到的两种相似度(self.sim_svd 和 self.sim_sgns)以及对应的词语对(self.word_vector)输出到一个名为 '2020522085.txt' 的文本文件中。 具体来说,代码首先创建了一个文件对象 f,指定其文件名为 '2020522085.txt',打开方式为写入('w'),并指定文件编码为 'utf-8'。接着,代码使用 pickle.load() 函数从之前保存的二进制文件 'sim_svd' 和 'sim_sgns' 中分别读取相似度列表 self.sim_svd 和 self.sim_sgns,注意需要使用二进制模式打开文件。然后,代码使用 for 循环遍历前 500 个词语对,将它们的词语和相似度信息以一定的格式写入文件 f 中。具体来说,对于每个词语对,代码将其两个词语使用空格连接起来,然后接上两个相似度值,中间使用若干个空格分隔,最后加上一个换行符。文件写入完成后,代码使用 f.close() 关闭文件对象。

相关推荐

import pandas as pd import numpy as np # 计算用户对歌曲的播放比例 triplet_dataset_sub_song_merged_sum_df = triplet_dataset_sub_song_mergedpd[['user', 'listen_count']].groupby('user').sum().reset_index() triplet_dataset_sub_song_merged_sum_df.rename(columns={'listen_count': 'total_listen_count'}, inplace=True) triplet_dataset_sub_song_merged = pd.merge(triplet_dataset_sub_song_mergedpd, triplet_dataset_sub_song_merged_sum_df) triplet_dataset_sub_song_mergedpd['fractional_play_count'] = triplet_dataset_sub_song_mergedpd['listen_count'] / triplet_dataset_sub_song_merged['total_listen_count'] # 将用户和歌曲编码为数字 small_set = triplet_dataset_sub_song_mergedpd user_codes = small_set.user.drop_duplicates().reset_index() song_codes = small_set.song.drop_duplicates().reset_index() user_codes.rename(columns={'index': 'user_index'}, inplace=True) song_codes.rename(columns={'index': 'song_index'}, inplace=True) song_codes['so_index_value'] = list(song_codes.index) user_codes['us_index_value'] = list(user_codes.index) small_set = pd.merge(small_set, song_codes, how='left') small_set = pd.merge(small_set, user_codes, how='left') # 将数据转换为稀疏矩阵形式 from scipy.sparse import coo_matrix mat_candidate = small_set[['us_index_value', 'so_index_value', 'fractional_play_count']] data_array = mat_candidate.fractional_play_count.values row_array = mat_candidate.us_index_value.values col_array = mat_candidate.so_index_value.values data_sparse = coo_matrix((data_array, (row_array, col_array)), dtype=float) # 使用SVD方法进行矩阵分解并进行推荐 from scipy.sparse import csc_matrix from scipy.sparse.linalg import svds import math as mt def compute_svd(urm, K): U, s, Vt = svds(urm, K) dim = (len(s), len(s)) S = np.zeros(dim, dtype=np.float32) for i in range(0, len(s)): S[i, i] = mt.sqrt(s[i]) U = csc_matrix(U, dtype=np.float32) S = csc_matrix(S, dtype=np.float32) Vt = csc_matrix(Vt, dtype=np.float32) return U, S, Vt def compute_estimated_matrix(urm, U, S, Vt, uTest, K, test): rightTerm = S * Vt max_recommendation = 250 estimatedRatings = np.zeros(shape=(MAX_UID, MAX_PID), dtype=np.float16) recomendRatings = np.zeros(shape=(MAX_UID, max_recommendation), dtype=np.float16) for userTest in uTest: prod = U[userTest, :] * rightTerm estimatedRatings[userTest, :] = prod.todense() recomendRatings[userTest, :] = (-estimatedRatings[userTest, :]).argsort()[:max_recommendation] return recomendRatings K = 50 urm = data_sparse MAX_PID = urm.shape[1] MAX_UID = urm.shape[0] U, S, Vt = compute_svd(urm, K) uTest = [4, 5, 6, 7, 8, 73, 23] # uTest=[1b5bb32767963cbc215d27a24fef1aa01e933025] uTest_recommended_items = compute_estimated_matrix(urm, U, S, Vt 继续将这段代码输出完整

将上述代码放入了Recommenders.py文件中,作为一个自定义工具包。将下列代码中调用scipy包中svd的部分。转为使用Recommenders.py工具包中封装的svd方法。给出修改后的完整代码。import pandas as pd import math as mt import numpy as np from sklearn.model_selection import train_test_split from Recommenders import * from scipy.sparse.linalg import svds from scipy.sparse import coo_matrix from scipy.sparse import csc_matrix # Load and preprocess data triplet_dataset_sub_song_merged = triplet_dataset_sub_song_mergedpd # load dataset triplet_dataset_sub_song_merged_sum_df = triplet_dataset_sub_song_merged[['user','listen_count']].groupby('user').sum().reset_index() triplet_dataset_sub_song_merged_sum_df.rename(columns={'listen_count':'total_listen_count'},inplace=True) triplet_dataset_sub_song_merged = pd.merge(triplet_dataset_sub_song_merged,triplet_dataset_sub_song_merged_sum_df) triplet_dataset_sub_song_merged['fractional_play_count'] = triplet_dataset_sub_song_merged['listen_count']/triplet_dataset_sub_song_merged['total_listen_count'] # Convert data to sparse matrix format small_set = triplet_dataset_sub_song_merged user_codes = small_set.user.drop_duplicates().reset_index() song_codes = small_set.song.drop_duplicates().reset_index() user_codes.rename(columns={'index':'user_index'}, inplace=True) song_codes.rename(columns={'index':'song_index'}, inplace=True) song_codes['so_index_value'] = list(song_codes.index) user_codes['us_index_value'] = list(user_codes.index) small_set = pd.merge(small_set,song_codes,how='left') small_set = pd.merge(small_set,user_codes,how='left') mat_candidate = small_set[['us_index_value','so_index_value','fractional_play_count']] data_array = mat_candidate.fractional_play_count.values row_array = mat_candidate.us_index_value.values col_array = mat_candidate.so_index_value.values data_sparse = coo_matrix((data_array, (row_array, col_array)),dtype=float) # Compute SVD def compute_svd(urm, K): U, s, Vt = svds(urm, K) dim = (len(s), len(s)) S = np.zeros(dim, dtype=np.float32) for i in range(0, len(s)): S[i,i] = mt.sqrt(s[i]) U = csc_matrix(U, dtype=np.float32) S = csc_matrix(S, dtype=np.float32) Vt = csc_matrix(Vt, dtype=np.float32) return U, S, Vt def compute_estimated_matrix(urm, U, S, Vt, uTest, K, test): rightTerm = S*Vt max_recommendation = 10 estimatedRatings = np.zeros(shape=(MAX_UID, MAX_PID), dtype=np.float16) recomendRatings = np.zeros(shape=(MAX_UID,max_recommendation ), dtype=np.float16) for userTest in uTest: prod = U[userTest, :]*rightTerm estimatedRatings[userTest, :] = prod.todense() recomendRatings[userTest, :] = (-estimatedRatings[userTest, :]).argsort()[:max_recommendation] return recomendRatings K=50 # number of factors urm = data_sparse MAX_PID = urm.shape[1] MAX_UID = urm.shape[0] U, S, Vt = compute_svd(urm, K) # Compute recommendations for test users # Compute recommendations for test users uTest = [1,6,7,8,23] uTest_recommended_items = compute_estimated_matrix(urm, U, S, Vt, uTest, K, True) # Output recommended songs in a dataframe recommendations = pd.DataFrame(columns=['user','song', 'score','rank']) for user in uTest: rank = 1 for song_index in uTest_recommended_items[user, 0:10]: song = small_set.loc[small_set['so_index_value'] == song_index].iloc[0] # Get song details recommendations = recommendations.append({'user': user, 'song': song['title'], 'score': song['fractional_play_count'], 'rank': rank}, ignore_index=True) rank += 1 display(recommendations)

import pandas as pd import math as mt import numpy as np from sklearn.model_selection import train_test_split from Recommenders import SVDRecommender triplet_dataset_sub_song_merged = triplet_dataset_sub_song_mergedpd triplet_dataset_sub_song_merged_sum_df = triplet_dataset_sub_song_merged[['user','listen_count']].groupby('user').sum().reset_index() triplet_dataset_sub_song_merged_sum_df.rename(columns={'listen_count':'total_listen_count'},inplace=True) triplet_dataset_sub_song_merged = pd.merge(triplet_dataset_sub_song_merged,triplet_dataset_sub_song_merged_sum_df) triplet_dataset_sub_song_merged['fractional_play_count'] = triplet_dataset_sub_song_merged['listen_count']/triplet_dataset_sub_song_merged small_set = triplet_dataset_sub_song_merged user_codes = small_set.user.drop_duplicates().reset_index() song_codes = small_set.song.drop_duplicates().reset_index() user_codes.rename(columns={'index':'user_index'}, inplace=True) song_codes.rename(columns={'index':'song_index'}, inplace=True) song_codes['so_index_value'] = list(song_codes.index) user_codes['us_index_value'] = list(user_codes.index) small_set = pd.merge(small_set,song_codes,how='left') small_set = pd.merge(small_set,user_codes,how='left') mat_candidate = small_set[['us_index_value','so_index_value','fractional_play_count']] data_array = mat_candidate.fractional_play_count.values row_array = mat_candidate.us_index_value.values col_array = mat_candidate.so_index_value.values data_sparse = coo_matrix((data_array, (row_array, col_array)),dtype=float) K=50 urm = data_sparse MAX_PID = urm.shape[1] MAX_UID = urm.shape[0] recommender = SVDRecommender(K) U, S, Vt = recommender.fit(urm) Compute recommendations for test users uTest = [1,6,7,8,23] uTest_recommended_items = recommender.recommend(uTest, urm, 10) Output recommended songs in a dataframe recommendations = pd.DataFrame(columns=['user','song', 'score','rank']) for user in uTest: rank = 1 for song_index in uTest_recommended_items[user, 0:10]: song = small_set.loc[small_set['so_index_value'] == song_index].iloc[0] # Get song details recommendations = recommendations.append({'user': user, 'song': song['title'], 'score': song['fractional_play_count'], 'rank': rank}, ignore_index=True) rank += 1 display(recommendations)这段代码报错了,为什么?给出修改后的 代码

class svd_recommender_py(): #svd矩阵推荐 def svds(A, ncv=None, tol=0, which='LM', v0=None, maxiter=None, return_singular_vectors=True, solver='arpack'): if which == 'LM': largest = True elif which == 'SM': largest = False else: raise ValueError("which must be either 'LM' or 'SM'.") if not (isinstance(A, LinearOperator) or isspmatrix(A) or is_pydata_spmatrix(A)): A = np.asarray(A) n, m = A.shape if k <= 0 or k >= min(n, m): raise ValueError("k must be between 1 and min(A.shape), k=%d" % k) if isinstance(A, LinearOperator): if n > m: X_dot = A.matvec X_matmat = A.matmat XH_dot = A.rmatvec XH_mat = A.rmatmat else: X_dot = A.rmatvec X_matmat = A.rmatmat XH_dot = A.matvec XH_mat = A.matmat dtype = getattr(A, 'dtype', None) if dtype is None: dtype = A.dot(np.zeros([m, 1])).dtype else: if n > m: X_dot = X_matmat = A.dot XH_dot = XH_mat = _herm(A).dot else: XH_dot = XH_mat = A.dot X_dot = X_matmat = _herm(A).dot def matvec_XH_X(x): return XH_dot(X_dot(x)) def matmat_XH_X(x): return XH_mat(X_matmat(x)) XH_X = LinearOperator(matvec=matvec_XH_X, dtype=A.dtype, matmat=matmat_XH_X, shape=(min(A.shape), min(A.shape))) # Get a low rank approximation of the implicitly defined gramian matrix. #获得隐式定义的格拉米矩阵的低秩近似。 #这不是解决问题的稳定方法。 solver == 'arpack' eigvals, eigvec = eigsh(XH_X, k=k, tol=tol ** 2, maxiter=maxiter, ncv=ncv, which=which, v0=v0) #格拉米矩阵具有实非负特征值。 eigvals = np.maximum(eigvals.real, 0) #使用来自pinvh的小特征值的复杂检测。 t = eigvec.dtype.char.lower() factor = {'f': 1E3, 'd': 1E6} cond = factor[t] * np.finfo(t).eps cutoff = cond * np.max(eigvals) #得到一个指示哪些本征对不是退化微小的掩码, #并创建阈值奇异值的重新排序数组。 above_cutoff = (eigvals > cutoff) nlarge = above_cutoff.sum() nsmall = k - nlarge slarge = np.sqrt(eigvals[above_cutoff]) s = np.zeros_like(eigvals) s[:nlarge] = slarge if not return_singular_vectors: return np.sort(s) if n > m: vlarge = eigvec[:, above_cutoff] ularge = X_matmat(vlarge) / slarge if return_singular_vectors != 'vh' else None vhlarge = _herm(vlarge) else: ularge = eigvec[:, above_cutoff] vhlarge = _herm(X_matmat(ularge) / slarge) if return_singular_vectors != 'u' else None u = _augmented_orthonormal_cols(ularge, nsmall) if ularge is not None else None vh = _augmented_orthonormal_rows(vhlarge, nsmall) if vhlarge is not None else None indexes_sorted = np.argsort(s) s = s[indexes_sorted] if u is not None: u = u[:, indexes_sorted] if vh is not None: vh = vh[indexes_sorted] return u, s, vh这段代码主要是为了将scipy包中的SVD计算方法封装成一个自定义类,是否封装合适?如果不合适,给出修改后的完整代码

最新推荐

recommend-type

7.22 软件版本说明(SVD).docx

基于GB∕T 8567-2006 《计算机软件文档编制规范》的要求转化出来的文件模板,可用于软件产品的设计开发,编制设计开发文档。
recommend-type

华中科技大学电信专业 课程资料 作业 代码 实验报告-数据结构-内含源码和说明书.zip

华中科技大学电信专业 课程资料 作业 代码 实验报告-数据结构-内含源码和说明书.zip
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

用 Python 画一个可以动的爱心

好的,我可以帮助您使用Python来绘制一个动态的爱心。您可以使用turtle库来实现。以下是实现代码: ```python import turtle import math # 设置画布和画笔 canvas = turtle.Screen() canvas.bgcolor("black") pencil = turtle.Turtle() pencil.speed(0) pencil.color("red", "pink") pencil.pensize(3) # 定义爱心函数 def draw_love(heart_size, x_offset=0, y_offset=0):
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。
recommend-type

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这
recommend-type

已知n个人(以编号0,1,2,3...n-1分别表示)围坐在一张圆桌周围。从编号为0的人开始报数1,数到m的那个人出列;他的下一个人又从1开始报数,数到m+1的那个人又出列(每次报数值加1);依此规律重复下去,直到圆桌周围的人全部出列。用递归方法解决

这个问题可以使用递归方法解决。下面是一个思路: 1. 定义一个函数,接收三个参数:n、m、i,表示还剩下n个人,每次数到m时出列,当前报数的人是i; 2. 如果n=1,返回i,即最后留下的那个人的编号; 3. 否则,计算出下一个出列的人的编号j,通过递归调用函数解决n-1个人的问题,其结果为k; 4. 如果k < j,即当前i之后出列的人的编号为k,需要将k转换为在i之前出列的编号,返回值为 k+(n-1); 5. 如果k>=j,即当前i之后出列的人的编号为k,返回值为 k-(j-1); 下面是对应的Python代码: ```python def josephus(n, m, i):