Tensorflow "ValueError: setting an array element with a sequence." in sess.run()



我目前正在开发一个程序,用于对手写字符的32x32图像进行分类。这是我到目前为止的代码:

import tensorflow as tf
import numpy as np
from PIL import Image
import csv
train_list = csv.reader(open("HCR_data/HCR_train_labels.csv"), delimiter=",")
test_list = csv.reader(open("HCR_data/HCR_test_labels.csv"), delimiter=",")
x = tf.placeholder(tf.float32, [None, 1024])
w = tf.Variable(tf.zeros([1024, 26]))
b = tf.Variable(tf.zeros([26]))
y = tf.nn.softmax(tf.matmul(x, w) + b)
y_ = tf.placeholder(tf.float32, [None, 26])
train_data = []
for location, label in train_list:
    image = Image.open(location).convert('L')
    image = np.asarray(image).flatten()
    image = [0.0 if p==255 else 1.0 for p in image]
    one_hot = [0.0] * 26
    one_hot[ord(label) - 65] = 1.0
    train_data.append((image, one_hot))
train_data = np.asarray(train_data)
np.random.shuffle(train_data)
test_data = []
for location, label in test_list:
    image = Image.open(location).convert('L')
    image = np.asarray(image).flatten()
    image = [0.0 if p==255 else 1.0 for p in image]
    one_hot = [0.0] * 26
    one_hot[ord(label) - 65] = 1.0
    test_data.append((image, one_hot))
test_data = np.asarray(test_data)
np.random.shuffle(test_data)
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
sess = tf.InteractiveSession()
tf.global_variables_initializer().run()
for i in range(269):
    batch_xs = train_data[(i*7):((i+1)*7),0]
    batch_ys = train_data[(i*7):((i+1)*7),1]
    #print(len(batch_ys)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
print(sess.run(accuracy, feed_dict={x: test_data[:,0], y_: test_data[:,1]}))

我基于 Tensorflow 网站上的 MNIST 教程,但是每当构建程序时,我都会收到错误:

Traceback (most recent call last):
  File "C:...HCR.py", line 57, in <module>
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
  File "C:...AppDataLocalProgramsPythonPython35libsite-packagestensorflowpythonclientsession.py", line 766, in run
run_metadata_ptr)
  File "C:...AppDataLocalProgramsPythonPython35libsite-packagestensorflowpythonclientsession.py", line 937, in _run
    np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
  File "C:...AppDataLocalProgramsPythonPython35libsite-packagesnumpycorenumeric.py", line 531, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.

请帮忙,我已经尝试了很多方法来更改我输入feed_dict的方式,但我无法弄清楚出了什么问题。Batch_xs应为 7x1024,batch_ys应为 7x26。我知道只有 7 个批次不会那么准确,但我想先弄清楚这个错误。

哈哈,好吧,大约 20 秒后我解决了自己的问题,只是注意到各个数组之间没有逗号。因此,每当我输入数组以feed_dict时,我都会在数组周围添加list(...)

旁注:我的准确性非常糟糕,53%...淳淑娴

更新:只需删除ytf.nn.softmax(...)即可将其提高到80%

相关内容

最新更新