python - 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 的一个例子:
解决方案
推荐阅读
- apache-spark - 具有 nutch 数据的本地模式下的 Apache Mahout 与 Apache Spark
- java - Spring Boot 控制器不重定向
- python-3.x - pytesseract 无法从图像中识别复杂的数学公式
- tensorflow - 在 tf.data.Dataset.map 中使用 tf.keras.applications.resnet50.preprocess_input 时出错
- python - ValueError:检查目标时出错:预期 dense_1 具有形状 (7, 7) 但得到的数组具有形状 (7, 1)
- android - Retrofit2 使用 Hashmap 发布和获取 Json 数组数据
- c# - 具有 basicHttpBinding、传输安全性和基本客户端凭据类型的自定义 WCF 凭据验证器
- ios - 实施新的谷歌纸板
- java - 在 JAVA 中查找 JSON 字符串的深度
- javascript - 如何在选项卡内执行一些 JavaScript 代码以使用 chrome 扩展更改页面的某些内容?