使用序列设置数组元素

使用序列设置数组元素

本文介绍了“ValueError:使用序列设置数组元素."TensorFlow的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图探索一个简单的演示,但遇到了这个错误.我该如何修改我的代码?

I tried to explore a simple demo,but got this error. How could I modify my code?

import tensorflow as tf

sess = tf.Session()

x_ = tf.Variable([[-9,6,-2,3], [-4,3,-1,10]], dtype=tf.float32)
x = tf.placeholder(tf.float32, shape=[4,2])
y = tf.nn.relu(x)

sess.run(tf.global_variables_initializer())
print(sess.run(x_))
print(sess.run(y,feed_dict={x:x_}))

我得到的输出是:

[[ -9.   6.  -2.   3.]
 [ -4.   3.  -1.  10.]]

Traceback (most recent call last):
  File "C:\Users\jy\Documents\NetSarang\Xftp\Temporary\test.py", line 19, in <module>
    print(sess.run(y,feed_dict={x:x_}))
  File "C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 767, in run
    run_metadata_ptr)
  File "C:\Program Files\Anaconda3\lib\site-packages\tensorflow\python\client\session.py", line 938, in _run
    np_val = np.asarray(subfeed_val, dtype=subfeed_dtype)
  File "C:\Program Files\Anaconda3\lib\site-packages\numpy\core\numeric.py", line 482, in asarray
    return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.

推荐答案

首先,你的 x_ 变量的维度不对:目前,它的形状是 [2, 4],但是您试图在需要形状为 [4, 2] 的数据的插槽中使用它.

First, the dimensionality of your x_ variable wrong: currently, it's of shape [2, 4], but you're attempting to use it in a slot that's expecting data of shape [4, 2].

其次,tf.Variable 旨在从字面上表示神经网络模型中的一个变量(在数学意义上),该变量将在您训练模型时进行调整——它是一种用于维护的机制状态.

Second, tf.Variable is meant to represent literally a variable (in the mathematical sense) within your neural net model that'll be tuned as you train your model -- it's a mechanism for maintaining state.

要提供实际输入来训练您的模型,您只需传入一个常规 Python 数组(或 numpy 数组)即可.

To provide actual input to train your model, you can simply pass in a regular Python array (or numpy array) instead.

这是您的代码的固定版本,似乎可以满足您的要求:

Here's a fixed version of your code that appears to do what you want:

import tensorflow as tf

sess = tf.Session()

x = tf.placeholder(tf.float32, shape=[4,2])
y = tf.nn.relu(x)
sess.run(tf.global_variables_initializer())

x_ = [[-9, -4], [6, 3], [-2, -1], [3, 10]]
print(sess.run(y, feed_dict={x:x_}))

如果你真的希望你的神经网络中的一个节点开始使用这些值进行初始化,我会去掉占位符并直接使用 x_:

If you really did want a node within your neural net to start off initialized with those values, I'd get rid of the placeholder and use x_directly:

import tensorflow as tf

sess = tf.Session()

x = tf.Variable([[-9, -4], [6, 3], [-2, -1], [3, 10]], dtype=tf.float32)
y = tf.nn.relu(x)
sess.run(tf.global_variables_initializer())

print(sess.run(y))

不过,这可能不是您想要做的——模型不接受任何输入是很不寻常的.

This is probably not what you meant to do, though -- it's sort of unusual to have a model that doesn't accept any input.

这篇关于“ValueError:使用序列设置数组元素."TensorFlow的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 10:08