当前位置:   article > 正文

tfRecord TypeError: only integer scalar arrays can be converted to a scalar index 错误解决办法

only integer scalar arrays can be converted to a scalar index

从网上找到一个通过numpy array生成tfrecord的代码,但是运行时报错,出现TypeError: only integer scalar arrays can be converted to a scalar index错误,原因是该记录为类型不匹配 需要从integer scalar arrays -> 单个int64数字

"""
原有问题代码如下,注释部分为正确代码
本程序演示了如何保存numpy array为TFRecords文件,并将其读取出来。
"""
import random

import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

def save_tfrecords(state_data, action_data, reward_data, dest_file):
    """
    保存numpy array到TFRecord文件中。
    这里输入了三个不同的numpy array来做演示,它们含有不同类型的元素。
    Args:
        state_data: 要保存到TFRecord文件的第1个numpy array,每一个 state_data[i] 是一个 numpy.ndarray(数组里的每个元素又是一个浮点
                    数),因此不能用 Int64List 或 FloatList 来存储,只能用 BytesList。
        action_data: 要保存到TFRecord文件的第2个numpy array,每一个 action_data[i] 是一个整数,使用 Int64List 来存储。
        reward_data: 要保存到TFRecord文件的第3个numpy array,每一个 reward_data[i] 是一个整数,使用 Int64List 来存储。
        dest_file: 输出文件的路径。
    Returns:
        不返回任何值
    """
    with tf.io.TFRecordWriter(dest_file) as writer:
        for i in range(len(state_data)):
            features = tf.train.Features(
                feature={
                    # 不同点1 也是可以用floatList的
                    #"state": tf.train.Feature(                 
                       #float_list=tf.train.FloatList(value=state_data[i].astype(np.float))),
                    "state": tf.train.Feature(
                        bytes_list=tf.train.BytesList(value=[state_data[i].astype(np.float32).tobytes()])),
                    "action": tf.train.Feature(
                        int64_list=tf.train.Int64List(value=[action_data[i]])),
                    "reward": tf.train.Feature(
                        int64_list=tf.train.Int64List(value=[reward_data[i]])) 
                    # 不同点2
                    # "action": tf.train.Feature(
                    #     int64_list=tf.train.Int64List(value=action_data[i].astype(np.int))),
                    # "reward": tf.train.Feature(
                    #     int64_list=tf.train.Int64List(value=reward_data[i].astype(np.int)))
                }
            )
            tf_example = tf.train.Example(features=features)
            serialized = tf_example.SerializeToString()
            writer.write(serialized)



if __name__ == '__main__':
    buffer_s, buffer_a, buffer_r = [], [], []

    # 随机生成一些数据
    for i in range(3):
        state = [round(random.random() * 100, 2) for _ in range(0, 10)]  # 一个数组,里面有10个数,每个都是一个浮点数
        action = random.randrange(0, 2)  # 一个数,值为 0 或 1
        reward = random.randrange(0, 100)  # 一个数,值域 [0, 100)
        # 把生成的数分别添加到3个list中
        buffer_s.append(state)
        buffer_a.append(action)
        buffer_r.append(reward)

        # 查看生成的数据
    print(buffer_s)
    print(buffer_a)
    print(buffer_r)

    # 在水平方向把各个list堆叠起来,堆叠的结果:得到3个矩阵
    s_stacked = np.vstack(buffer_s)
    a_stacked = np.vstack(buffer_a)
    r_stacked = np.vstack(buffer_r)

    print(s_stacked.shape)  # (3, 10)
    print(a_stacked.shape)  # (3, 1)
    print(r_stacked.shape)  # (3, 1)


    print(s_stacked)
    print(a_stacked)
    print(r_stacked)


    print("data generate sucess!")

    # 写入TFRecord文件
    output_file = './data.tfrecord'  # 输出文件的路径
    save_tfrecords(s_stacked, a_stacked, r_stacked, output_file)

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88

原始代码块:
action:为
[[0]
[1]
[1]]
通过切片操作获取其中的一个元素,这个元素也是list,所以不需要再强制转为list,通过 .astype(np.int) 转为具体类型

参考链接:
【1】numpy数组TypeError:只能将整数标量数组转换为标量索引(numpy array TypeError: only integer scalar arrays can be converted to a scalar index)
【2】Numpy中stack(),hstack(),vstack()函数详解

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/700923
推荐阅读
相关标签
  

闽ICP备14008679号