python - 运行神经网络代码时出现值错误

标签 python numpy tensorflow deep-learning

我正在尝试创建一个神经网络模型来预测签名是真实的还是假的。我创建了包含 1044 个签名的数据集,其中包含真签名和假签名。这是图像预处理的代码

DATA = '../DATASET/DATA/'
IMG_BREDTH = 150
IMG_HEIGHT = 70

# helper functions
def label_img(img):
    word_label = img.split('.')[-2]
    if (word_label == '1') or (word_label == '2'): return [1,0]
    elif word_label == 'F': return [0,1]

def create_data_set():
    data = []

    for img in tqdm(os.listdir(DATA)):

        if img == '.DS_Store': continue

        label = label_img(img)
        path = os.path.join(DATA, img)
        img = cv2.resize(cv2.imread(path, cv2.IMREAD_GRAYSCALE), (IMG_HEIGHT, IMG_BREDTH))
        data.append([np.array(img), label])

    shuffle(data)
    np.save('data.npy', data)

    return np.array(data)

然后我使用此代码将数据分成训练集和测试集

data = create_data_set()
train_x = data[:835, 0]
train_y = data[:835, 1]
test_x = data[835:, 0]
test_y = data[835:, 1]

train_x 现在包含 835 个图像,train_y 包含各自的标签([1,0] 表示正品,[0,1] 表示假品)。 train_x 中每个图像的形状为 (150, 70)。 train_y 的 shpae 为 (835, )

然后我用这段代码创建了神经网络

n_nodes_hl1 = 500
n_nodes_hl2 = 500
n_nodes_hl3 = 500
n_classes = 2
batch_size = 100

x = tf.placeholder(tf.float32, [None, len(train_x[0])])
y = tf.placeholder(tf.float32)

# neural network model
def neural_network_model(data):
    hidden_layer_1 = {'weights': tf.Variable(tf.random_normal([len(train_x[0]), n_nodes_hl1])),
                      'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))}

    hidden_layer_2 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                      'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))}

    hidden_layer_3 = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                      'biases': tf.Variable(tf.random_normal([n_nodes_hl3]))}

    output_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
                    'biases': tf.Variable(tf.random_normal([n_classes]))}

    l1 = tf.add(tf.matmul(data, hidden_layer_1['weights']), hidden_layer_1['biases'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1, hidden_layer_2['weights']), hidden_layer_2['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2, hidden_layer_3['weights']), hidden_layer_3['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3, output_layer['weights']) + output_layer['biases']

    return output

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y) )
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 10
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0

            i = 0
            while i < len(train_x):
                start = i
                end = i + batch_size

                batch_x = np.array(train_x[start:end], object)
                batch_y = np.array(train_y[start:end], object)
                assert batch_x.shape == (100, )
                _, c = sess.run(fetches=[optimizer, cost], feed_dict={x: batch_x, y: batch_y})
                epoch_loss += c

                i += batch_size

            print('Epoch', epoch, 'completed out of', hm_epochs, 'loss', epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        print('Accuracy: ', accuracy.eval({x: test_x, y: test_y}))

batch_x 的形状为 (100, ),batch_y 的形状为 (100, )。当我运行程序时出现以下错误

train_neural_network(x)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-32-7c7cbdae9b34> in <module>()
----> 1 train_neural_network(x)

<ipython-input-31-041caea3bd1c> in train_neural_network(x)
     20                 print(batch_y.shape)
     21                 assert batch_x.shape == (100, )
---> 22                 _, c = sess.run(fetches=[optimizer, cost], feed_dict={x: batch_x, y: batch_y})
     23                 epoch_loss += c
     24 

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    952             np_val = subfeed_val.to_numpy_array()
    953           else:
--> 954             np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
    955 
    956           if (not is_tensor_handle_feed and

~/anaconda3/lib/python3.6/site-packages/numpy/core/numeric.py in asarray(a, dtype, order)
    529 
    530     """
--> 531     return array(a, dtype, copy=False, order=order)
    532 
    533 

ValueError: setting an array element with a sequence.

我做错了什么?请注意,我是一名新手开发人员,刚刚开始学习神经网络。我在网上查看了特定错误并找到了以下链接。

"ValueError: setting an array element with a sequence." TensorFlow

Value Error while feeding in Neural Network

ValueError: setting an array element with a sequence

我尝试按照他们在答案中指定的方式进行操作,但它对我不起作用。

有人可以帮我吗

提前谢谢

编辑1: 发布此内容后,我查看了另一个具有类似问题的链接。 Tensorflow "ValueError: setting an array element with a sequence." in sess.run() 我尝试更改答案,但现在收到不同的错误。

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-36-7c7cbdae9b34> in <module>()
----> 1 train_neural_network(x)

<ipython-input-35-ac9b2062de7f> in train_neural_network(x)
     20                 print(batch_y.shape)
     21                 assert batch_x.shape == (100, )
---> 22                 _, c = sess.run(fetches=[optimizer, cost], feed_dict={x: list(batch_x), y: list(batch_y)})
     23                 epoch_loss += c
     24 

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    776     try:
    777       result = self._run(None, fetches, feed_dict, options_ptr,
--> 778                          run_metadata_ptr)
    779       if run_metadata:
    780         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

~/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    959                 'Cannot feed value of shape %r for Tensor %r, '
    960                 'which has shape %r'
--> 961                 % (np_val.shape, subfeed_t.name, str(subfeed_t.get_shape())))
    962           if not self.graph.is_feedable(subfeed_t):
    963             raise ValueError('Tensor %s may not be fed.' % subfeed_t)

ValueError: Cannot feed value of shape (100, 150, 70) for Tensor 'Placeholder_2:0', which has shape '(?, 150)'

我做错了什么?

最佳答案

错误消息只是表明您在运行优化算法和成本函数(通过 feed_dict)时向占位符 y 提供了错误的维度。检查尺寸是否正确。

关于python - 运行神经网络代码时出现值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49379448/

相关文章:

python - 如何使用可变补丁大小的 tf.random_crop 定义形状?

python - 在 TensorFlow 中,如何沿着参差不齐的维度索引参差不齐的张量?

python - 为什么我在使用 super() 时必须指定我自己的类,有没有办法绕过它?

python - Pyinstaller 单个 exe 无法正常工作,显然,有很多人遇到 Unresolved 问题

python - mongodb:如果不存在则插入

python-2.7 - 3 维 numpy 数组到多索引 Pandas 数据框

c++ - 什么是使用 opencv::Mat 优化 c++ 矩阵计算

python - SQL炼金术。创建共享枚举的表

javascript - 将 Blob 数据从 javascript 转换为在 python 中使用 opencv 读取

Rust 中的 TensorFlow, Unresolved 导入