gpt4 book ai didi

python - 如何解压 pkl 文件?

转载 作者:太空宇宙 更新时间:2023-11-03 21:14:15 26 4
gpt4 key购买 nike

我需要解压 pkl 文件,但由于我不熟悉 pickle 和 pandas,所以我很难做到这一点。

pkl 文件的内容类似于:

{
'woodi': array([-0.07377538, 0.01810472, 0.03796827, -0.01185564, -0.12605625,
-0.03709966, 0.07863396, 0.04245366, -0.09158159, -0.01418831,
-0.03165198, -0.01235643, 0.00833164, -0.08156401, -0.10466748,
0.11343367, -0.1291647 , 0.02277501, -0.12230705, 0.08400519,
0.01631752, -0.03204752, -0.10115118, 0.01796065, -0.08914784,
0.00336748, 0.02858992, 0.13387977, -0.01711662, -0.05058149,
0.09866285, 0.00623399, -0.11368696, 0.03389056, 0.03049786,
-0.11235228, 0.03964651, 0.18348881, 0.00356622, -0.09299972,
0.11804404, 0.10598116, 0.04603285, 0.10211086, -0.07094006,
0.19667923, -0.22645354, -0.02930884, -0.21891772, -0.07495865]),
'bad-boy': array([-0.01525861, -0.0145514 , 0.02207321, 0.01273549, 0.0034881 ,
-0.00045474, 0.01104943, 0.00057228, -0.01515725, 0.00329882,
0.01570324, -0.03927545, 0.00393151, 0.00355666, -0.00503297,
-0.01088151, -0.0354947 , -0.010477 , -0.01945165, 0.0312498 ,
0.00195288, -0.03095445, -0.00803227, 0.02864361, -0.01416729,
0.00375061, 0.00546439, 0.03621898, 0.01337988, -0.03205173,
0.00451094, 0.02180656, -0.02587242, -0.01276209, 0.02721113,
-0.00075289, -0.00218841, 0.00531534, -0.0074188 , 0.00312647,
0.00424174, 0.02444418, 0.0222739 , -0.00477895, 0.02220114,
0.03402764, -0.02423164, 0.00724037, -0.03526915, 0.01470344]),
...
}

我需要获取单词和每个单词的实值向量并创建一个 csv 文件...csv 文件的内容必须如下所示:

woodi -0.07377538 0.01810472 ... -0.07495865
bad-boy -0.01525861 -0.0145514 ... 0.01470344

我尝试过这个Python代码:

import pickle
import pandas as pd

fin = 'SGlove.pkl'
fout = 'SGlove.csv'

words, embeddings = pickle.load(open(fin, 'rb'), encoding='latin1')

m, n = embeddings.shape
print("Emebddings contains {} words embedded as vectors of length {}".format(m, n))

df = pd.DataFrame(embeddings)
df.insert(0, "word", words)
df.to_csv(fout, header=False, index=False, sep=" ")

但我收到以下错误消息:

Traceback (most recent call last):
File "pkl_to_csv.py", line 10, in <module>
words, embeddings = pickle.load(open(fin, 'rb'), encoding='latin1')
ValueError: too many values to unpack (expected 2)

最佳答案

martineau 大部分时间都在那里。 pickle.load() 返回一个字典,您需要对其进行额外的工作才能获取单词和嵌入。

你可以从

开始
import pickle

fin = 'SGlove.pkl'

data_dict = pickle.load(open(fin, 'rb'), encoding='latin1')

单词列表由下式给出

word_list = list(data_dict.keys())

然后您可以使用以下方法获取相应的嵌入列表

embedding_list = [data_dict[word] for word in word_list]

如果您需要所有单词的嵌入的二维数组,则需要使用 np.concatenate 或 embedding_list 上的类似内容来获取一个。例如,如果您希望嵌入的形状为 [n_words, len_vector] (如您所希望的),您可以使用

embeddings = np.concatenate([item[None, :] for item in embedding_list], axis=0)

关于python - 如何解压 pkl 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54836257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com