【问题标题】:ValueError when training Tensorflow: setting an array element with a sequence训练Tensorflow时出现ValueError:使用序列设置数组元素
【发布时间】:2016-02-17 04:50:20
【问题描述】:

我被 ValueError 困在训练过程中。 详情如下:

我做了如下标记。

flags = tf.app.flags
FLAGS = flags.FLAGS

flags.DEFINE_string('train', 'train.txt', 'File name of train data')
flags.DEFINE_string('test', 'test.txt', 'File name of train data')
flags.DEFINE_string('train_dir', '/tmp/data', 'Directory to put the training data.')
flags.DEFINE_integer('max_steps', 200, 'Number of steps to run trainer.')
flags.DEFINE_integer('batch_size', 10, 'Batch size'
                     'Must divide evenly into the dataset sizes.')
flags.DEFINE_float('learning_rate', 1e-4, 'Initial learning rate.')

另外训练过程如下:

if 1==1:
        # Tensor for images
    images_placeholder = tf.placeholder("float", shape=(None, IMAGE_PIXELS))
        # Tensor for labels
        labels_placeholder = tf.placeholder("float", shape=(None, NUM_CLASSES))
        # dropout rate
        keep_prob = tf.placeholder("float")

        # call inference() 
        logits = inference(images_placeholder, keep_prob)
        # call loss()
        loss_value = loss(logits, labels_placeholder)
        # call training()
        train_op = training(loss_value, FLAGS.learning_rate)
        # calculate accuract
        acc = accuracy(logits, labels_placeholder)

        # prepare for saving
        saver = tf.train.Saver()
        # make Session
        sess = tf.Session()
        # initialize variables
        sess.run(tf.initialize_all_variables())
        # values on TensorBoard
        summary_op = tf.merge_all_summaries()
        summary_writer = tf.train.SummaryWriter(FLAGS.train_dir, sess.graph_def)

        # Training process
        for step in range(FLAGS.max_steps):
            for i in range(len(train_image)/FLAGS.batch_size):
                # batch_size
                batch = FLAGS.batch_size*i
                # define data in placeholder by feed dict
                sess.run(train_op, feed_dict={
                images_placeholder:train_image[batch:batch+FLAGS.batch_size],
        labels_placeholder: train_label[batch:batch+FLAGS.batch_size],
                keep_prob: 0.5})

当我运行此代码时,我遇到了以下错误。如何解决这个问题?

File "CNN_model.py", line 230, in <module>
    images_placeholder: train_image[batch:batch+FLAGS.batch_size],labels_placeholder: train_label[batch:batch+FLAGS.batch_size],keep_prob: 0.5})
File "/Library/Python/2.7/site-packages/tensorflow/python/client/session.py", line 334, in run
    np_val = np.array(subfeed_val, dtype=subfeed_t.dtype.as_numpy_dtype)
ValueError: setting an array element with a sequence.

我在 train_image 和 train_label 周围添加代码如下。

 

NUM_CLASSES = 5
IMAGE_SIZE = 599
IMAGE_PIXELS = IMAGE_SIZE*1*128

  

f = open("song_features.json")
 data = json.load(f)
 data = np.array(data)

 flatten_data = []
 flatten_label = []


 for line in range(len(data)):
     for_flat = np.array(data[line])
     flatten_data.append(for_flat.flatten().tolist())

     #label made as 1-of-K
     tmp = np.zeros(NUM_CLASSES)
     tmp[int(random.randint(0,4))] = 1
        flatten_label.append(tmp)

  #1 line training data
  train_image = np.asarray(flatten_data)
  train_label = np.asarray(flatten_label)

我正在构建这个模型。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    当 TensorFlow 将 feed_dict 中的值转换为密集的 NumPy ndarrays 时会引发此异常,这将取决于您的 train_imagetrain_label 对象中的内容。

    这些错误的一个常见原因是当提要值是一个参差不齐的列表:即列表的列表,其中子列表具有不同的大小。例如:

    >>> train_image = [[1., 2., 3.], [4., 5.]]
    >>> np.array(train_image, dtype=np.float32)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: setting an array element with a sequence.
    

    编辑:感谢您分享构建train_imagetrain_label 的代码。我怀疑问题出在train_image 的创建中,如果flatten_data 的元素对于每个示例可以具有不同的长度。尝试进行以下修改以确认这一点:train_image = np.asarray(flatten_data, dtype=np.float32)。如果您得到相同的ValueError,则需要填充或裁剪各个行,以便它们具有IMAGE_PIXELS 元素。

    【讨论】:

    • 感谢您的支持。我在 train_image 和 train_label 周围添加了代码。
    • 感谢分享额外代码!我用一些建议更新了答案。
    • 我试过 train_image = np.asarray(flatten_data, dtype=np.float32) 但是,我得到了同样的错误。这次我添加了大约 NUM_PIXELS 个代码。
    • 尝试在附加到 flatten_data 之前添加 assert for_flat.flatten().shape == (NUM_PIXELS,)。这应该会找到任何尺寸错误的图像。
    猜你喜欢
    • 1970-01-01
    • 2016-10-31
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-25
    • 2016-08-13
    • 2023-03-16
    相关资源
    最近更新 更多