简体   繁体   English

unhashable类型:tensorflow中的'numpy.ndarray'错误

[英]unhashable type: 'numpy.ndarray' error in tensorflow

data = pd.read_excel("/Users/madhavthaker/Downloads/Reduced_Car_Data.xlsx")

train = np.random.rand(len(data)) < 0.8

data_train = data[train]
data_test = data[~train]


x_train = data_train.ix[:,0:3].values
y_train = data_train.ix[:,-1].values
x_test = data_test.ix[:,0:3].values
y_test = data_test.ix[:,-1].values

y_label = tf.placeholder(shape=[None,1], dtype=tf.float32, name='y_label')
x = tf.placeholder(shape=[None,3], dtype=tf.float32, name='x')
W = tf.Variable(tf.random_normal([3,1]), name='weights')
b = tf.Variable(tf.random_normal([1]), name='bias')
y = tf.matmul(x,W)  + b

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    summary_op = tf.summary.merge_all()
    #Fit all training data
    for epoch in range(1000):
        sess.run(train, feed_dict={x: x_train, y_label: y_train})

        # Display logs per epoch step
        if (epoch+1) % display_step == 0:
            c = sess.run(loss, feed_dict={x: x_train, y_label:y_train})
            print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(c), \
                "W=", sess.run(W), "b=", sess.run(b))

    print("Optimization Finished!")
    training_cost = sess.run(loss, feed_dict={x: x_train, y_label: y_train})
    print("Training cost=", training_cost, "W=", sess.run(W), "b=", sess.run(b), '\n')

Here is the error: 这是错误:

x---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-37-50102cbac823> in <module>()
      6     #Fit all training data
      7     for epoch in range(1000):
----> 8         sess.run(train, feed_dict={x: x_train, y_label: y_train})
      9 
     10         # Display logs per epoch step

TypeError: unhashable type: 'numpy.ndarray'

Here are the shapes of both of the numpy arrays that I am inputting: 以下是我输入的两个numpy数组的形状:

y_train.shape = (78,)
x_train.shape = (78, 3)

I have no idea what is causing this. 我不知道造成这种情况的原因。 All of my shapes match up and I shouldn't have any issues. 我的所有形状都匹配,我不应该有任何问题。 Let me know if you need any more information. 如果您需要更多信息,请与我们联系。

Edit: From my comment on one of the answers below, it seems as though I had to specify a specific size for my placeholders. 编辑:从我对下面其中一个答案的评论,似乎我必须为我的占位符指定一个特定的大小。 None was not satisfactory. None人不满意。 When I changed that and re-ran my code, everything worked fine. 当我改变它并重新运行我的代码时,一切正常。 Still not quite sure why that is. 仍然不太确定为什么会这样。

In my case, the problem was naming the input parameter the same as the placeholder variable. 在我的例子中,问题是将输入参数命名为与占位符变量相同。 This, of course, replaces your tensorflow variable with the input variable; 当然,这会用输入变量替换tensorflow变量; resulting in a different key for the feed_dict. 导致feed_dict的不同键。

A tensorflow variable is hashable, but your input parameter (np.ndarray) isn't. tensorflow变量是可清除的,但您的输入参数(np.ndarray)不是。 The unhashable error is therefore a result of you trying to pass your parameter as the key instead of a tensorflow variable. 因此,不可用的错误是您尝试将参数作为键而不是tensorflow变量传递的结果。 Some code to visualize what I'm trying to say: 一些代码可视化我想说的内容:

a = tf.placeholder(dtype=tf.float32, shape=[1,2,3])
b = tf.identity(a)

with tf.Session() as sess:
    your_var = np.ones((1,2,3))
    a = your_var
    sess.run(b, feed_dict={a: a})

Hopes this helps anyone stumbling upon this problem in the future! 希望这可以帮助任何人在将来绊倒这个问题!

Please carefully check the datatype you feed "x_train/y_train" and the tensor "x/y_label" you defined by 'tf.placeholder(...)' 请仔细检查您输入“x_train / y_train”的数据类型以及由'tf.placeholder(...)'定义的张量“x / y_label”

I have met the same problem with you. 我遇到了同样的问题。 And the reason is x_train in my code is "np. float64 ", but what I defined by tf.placeholder() is tf. 而原因就是x_train在我的代码是“NP。float64”,但我通过tf.placeholder定义(什么)为TF。 float32 . float32 The date type float64 and float32 is mismatching. 日期类型float64和float32不匹配。

I think problem is in defining the dictionary. 我认为问题在于定义字典。 A dictionary key has to be a 'hashable type', eg a number, a string or a tuple are common. 字典键必须是“可散列类型”,例如数字,字符串或元组是常见的。 A list or an array don't work: 列表或数组不起作用:

In [256]: {'x':np.array([1,2,3])}
Out[256]: {'x': array([1, 2, 3])}
In [257]: x=np.array([1,2,3])
In [258]: {x:np.array([1,2,3])}
...
TypeError: unhashable type: 'numpy.ndarray'

I don't know enough of tensorflow to know what these are: 我不知道张量流是否足以知道它们是什么:

y_label = tf.placeholder(shape=[None,1], dtype=tf.float32, name='y_label')
x = tf.placeholder(shape=[None,3], dtype=tf.float32, name='x')

The error indicates that they are are numpy arrays, not strings. 该错误表明它们是numpy数组,而不是字符串。 Does x have a name attribute? x是否具有name属性?

Or maybe the dictionary should be specified as: 或者字典应该指定为:

{'x': x_train, 'y_label': y_train}

Strange, I had this issue too. 奇怪,我也有这个问题。 After I close python shell and run the code from a file I didn't succeed to reproduce it even in the shell (it just works w/o an error). 在我关闭python shell并从文件中运行代码后,即使在shell中也没有成功重现它(它只是没有错误)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM