首页 > 解决方案 > numpy frombuffer() 和 tostring() - 从 csv 读取

问题描述

我已经在这几个小时了,四处寻找,对我的具体问题没有一个像样的答案。

所以,我正在为强化学习模型构建一个训练集,我想将该训练集保存到一个 csv 文件中。训练集的每条记录的形式为,

[np.ndarray(shape=(18,8,8)), np.ndarray(shape=(1968,)), int64]

神经网络的输入是一个 18x8x8 张量/numpy 数组,输出是一个平面数组 (1968) 策略 + 一个整数值。

当我将其写入csv文件时,我对每条记录的输入和策略元素使用以下 numpy 函数:

    input_bytes = inputs.tobytes() # inputs.tostring() also works
    policy_bytes = policy.tobytes() # same here, policy.tostring()

到了训练时间,我需要从 csv 文件中读取这些列,并将字节转换回 numpy.ndarray对象。我知道原始数据类型和形状 -用于输入和,np.int32用于策略。所以,你会认为我可以简单地使用:(18,8,8)np.float64(1968,)

    # need to use *_bytes[1:] because the 'b' character is written
    # to the csv when we save
    inputs = np.reshape(np.fromstring(input_bytes[1:], dtype=np.int32), (18,8,8))
    policy = np.fromstring(policy_bytes[1:], dtype=np.float64)

这失败了,给出了错误:

ValueError: string size must be a multiple of element size

如果我尝试将字符串转换为字节,并使用frombuffer,即

    inputs = np.reshape(np.frombuffer(bytes(input_bytes[1:], 'utf-8'), dtype=np.int32), (18,8,8))
    policy = np.frombuffer(bytes(policy_bytes[1:], 'utf-8'), dtype=np.float64)

我基本上得到了完全相同的错误。

ValueError: buffer size must be a multiple of element size

我意识到这一定是某种编码问题,但我无法准确指出。请注意,以下内容完美运行:

test_input = np.zeros(shape=(18,8,8), dtype=np.int32).tobytes()
test_policy = np.zeros(shape=(1968,), dtype=np.float64).tobytes()

np.reshape(np.frombuffer(test_input, dtype=np.int32), (18,8,8))
np.frombuffer(test_policy, dtype=np.float64)

如何将字节写入csv文件,并稍后通过读取文件将它们加载回 ndarray 对象?

编辑:这是 csv 的一个例子:

csv头

标签: pythonnumpy

解决方案


推荐阅读