如何从CSV文件中将词嵌入向量导入为float32格式?
问题描述
我当前正在做一个项目,需要生成指定语言的全名词列表对应的词嵌入向量。我原本计划将词汇表输入Word2Vec模型得到向量后存入CSV文件,后续直接用pd.read_csv方法导入以节省时间,但无论如何尝试,pandas始终将向量列识别为字符串而非float32类型。我已经尝试过传入dtype = np.float32参数,也试过先导入为字符串再强制转换列类型,均未成功。
读取代码
filepath = r"C:\Users\name\Word Embedding Plots\Spanish\full_list_Spanish.csv" df = pd.read_csv(filepath, index_col=0, dtype = {'labels':str,'vector':np.float32,'noun class':int,'cluster labels':int})
报错信息
TypeError Traceback (most recent call last) pandas\_libs\parsers.pyx in pandas._libs.parsers.TextReader._convert_tokens() TypeError: Cannot cast array data from dtype('O') to dtype('float32') according to the rule 'safe' During handling of the above exception, another exception occurred: ValueError Traceback (most recent call last) <ipython-input-73-00320472335a> in <module> 1 filepath = r"C:\Users\name\Word Embedding Plots\Spanish\full_list_Spanish.csv" ----> 2 df = pd.read_csv(filepath, index_col=0, dtype = {'labels':str,'vector':np.float32,'noun class':int,'cluster labels':int}) # 中间报错栈省略 ValueError: could not convert string to float: '[ 5.26622403e-03 2.76202578e-02 -2.03670934e-04 -1.64115373e-02\n 6.28665928e-03 -1.83933843e-02 3.29369050e-03 -2.29671989e-02\n ...(内容省略)'
预期格式
label vector \ 0 1 Crónicas [ 5.26622403e-03 2.76202578e-02 -2.03670934e-... 1 1 Juan [-4.13045213e-02 -3.40997241e-04 6.59986138e-... ... ... ... 27325 zwingliana [-1.19532188e-02 -2.14482211e-02 9.92432088e-... noun class cluster labels 0 0.0000 3.0000 1 0.0000 3.0000 ... ... ... 27325 1.0000 2.0000 [60934 rows x 4 columns]
提问
是否可以将向量直接导入为float32数组?
解决方案
核心原因
CSV是纯文本格式,你存入的向量会被序列化为带方括号、换行符的字符串,pandas的read_csv没有办法直接将这种整体字符串识别为float32数组,所以直接指定dtype会报错。
方案1:处理现有CSV文件
先按字符串读取vector列,再手动转换为float32数组:
import ast import numpy as np import pandas as pd # 先读取文件,暂时不指定vector列的类型 filepath = r"C:\Users\name\Word Embedding Plots\Spanish\full_list_Spanish.csv" df = pd.read_csv(filepath, index_col=0, dtype = {'labels':str,'noun class':int,'cluster labels':int}) # 转换vector列:先清除换行符、解析字符串为列表,再转成float32格式的numpy数组 df['vector'] = df['vector'].apply(lambda x: np.array(ast.literal_eval(x.replace('\n', '')), dtype=np.float32))
方案2:更优的长期存储方案
不要用CSV存储带有数组类型的DataFrame,推荐使用pickle格式,存储和读取都会保留原始数据类型,不需要额外转换,效率也更高:
# 存储 df.to_pickle("full_list_Spanish.pkl") # 读取,直接得到和存储时完全一致的类型,vector列直接就是float32数组 df = pd.read_pickle("full_list_Spanish.pkl")
内容的提问来源于stack exchange,提问作者Ardianor
相关产品推荐
相关产品推荐

