我正在使用下面定义的 export_vectors
保存一个 numpy 数组。在此函数中,我加载以空格分隔的字符串值,然后将它们作为 float 存储在 numpy 数组中。
def export_vectors(vocab, input_filename, output_filename, dim):
embeddings = np.zeros([len(vocab), dim])
with open(input_filename) as f:
for line in f:
line = line.strip().split(' ')
word = line[0]
embedding = line[1:]
if word in vocab:
word_idx = vocab[word]
embeddings[word_idx] = np.asarray(embedding).astype(float)
np.savez_compressed(output_filename, embeddings=embeddings)
这里的embeddings
是float64
类型的ndarray
。
虽然,然后在尝试加载文件时,使用:
def get_vectors(filename):
with open(filename) as f:
return np.load(f)["embeddings"]
尝试加载时出现错误:
File "/usr/lib/python3.5/codecs.py", line 321, in decode (result, consumed) = self._buffer_decode(data, self.errors, final) UnicodeDecodeError: 'utf-8' codec can't decode byte 0x99 in position 10: invalid start byte
这是为什么?
最佳答案
您可能错误地使用了open
。
我怀疑,你需要给它一个标志来使用 binary-mode 就像( docs ):
open(filename, 'rb') # r: read-only; b: binary
文档解释了默认行为:通常,文件以文本模式打开,这意味着您从文件读取和写入字符串,这些字符串以特定编码进行编码。
但是你可以让它变得简单,只使用文件路径本身(因为 np.load 能够采用类似文件的对象、字符串或 pathlib.Path
):
np.load(filename) # This would be more natural
# as it's kind of the direct inverse of your save-code;
# -> no manual file-handling
(一个简化的规则:所有使用通用压缩的东西总是使用二进制文件;而不是文本文件!)
关于python - 如何加载使用 numpy.savez_compressed 创建的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43282547/