使用reshape和flatten后,TensorFlow feed_dict仍报numpy数组不可哈希错误
问题原因及解决方案
嘿,这个错误我太熟了!咱们直接点破问题核心:
错误根源
你在feed_dict里犯了一个典型的混淆错误——把numpy数组x2当成了键,但TensorFlow的feed_dict要求键必须是TensorFlow的tf.placeholder(或其他可馈送的Tensor对象),而numpy数组是不可哈希(unhashable)的类型,所以才会抛出这个错误。
简单来说:
tf.placeholder是模型定义时预留的「输入插槽」- numpy数组是你要喂进这个插槽的实际数据
你现在相当于把「数据」直接往「插槽的位置」上怼,完全搞反了两者的角色。
另外你的代码还有个小坑:y_embedding = np.reshape(tf.nn.embedding_lookup(W, y), [1,-1])这里用了np.reshape处理TensorFlow张量,这是不对的——TensorFlow张量得用TensorFlow自己的tf.reshape来操作,不能混用numpy的函数。
修正后的代码示例
我帮你把核心错误点修正了,你可以参考这个结构:
import nltk import numpy as np import tensorflow as tf sent_toks = nltk.sent_tokenize(ctxt) x2 = np.array(list(vocab_processor.transform(sent_toks))) y_data = np.array(list(vocab_processor.transform(<some other string>))) def NHIDDEN(): return 1 def NINPUT(): return 50 vocab_size = len(vocab_processor.vocabulary_) # 假设你有这个词汇表大小 g = tf.Graph() tf.reset_default_graph() with g.as_default(): # 第一步:定义模型的输入占位符!这是解决错误的关键 x_ph = tf.placeholder(tf.int32, shape=[-1, NINPUT()], name="input_x") y_ph = tf.placeholder(tf.int32, shape=[None], name="input_y") # 假设W是你的嵌入矩阵(预训练或随机初始化) W = tf.Variable(tf.random_uniform([vocab_size, NINPUT()], -1.0, 1.0), name="embedding_matrix") # 正确处理y的嵌入:用tf.reshape而非np.reshape y_embedding = tf.reshape(tf.nn.embedding_lookup(W, y_ph), [1, -1]) # 这里补上你原来的模型结构(RNN层、损失函数、优化器等) # 比如: # rnn_cell = tf.nn.rnn_cell.BasicRNNCell(NHIDDEN()) # outputs, _ = tf.nn.dynamic_rnn(rnn_cell, x_ph, dtype=tf.float32) # pred = ... # 你的预测层 # cost = ... # 你的损失函数 # optimizer = tf.train.AdamOptimizer().minimize(cost) with tf.Session(graph=g) as sess: # 别忘了初始化所有变量! sess.run(tf.global_variables_initializer()) step = 0 loss_total = 0.0 training_iters = 1 while step < training_iters: # 预处理数据成符合占位符的形状 x_processed = np.reshape(x2.flatten(), [-1, NINPUT()]) # 关键:feed_dict的键是占位符,值是numpy数组 _, loss, pred_ = sess.run([optimizer, cost, pred], feed_dict={x_ph: x_processed, y_ph: y_data}) loss_total += loss print(f"loss = {loss_total:.6f}") step += 1 print("Finished Optimization")
核心注意点
- 永远记得先定义
tf.placeholder作为模型的输入接口,feed_dict的键只能是这些占位符(或TensorFlow生成的张量) - 区分清楚「模型的输入节点」和「要喂入的数据」:前者是TensorFlow对象,后者是numpy数组
- 在TensorFlow的图定义阶段,所有张量操作都要用TensorFlow的API,别混用numpy的函数
内容的提问来源于stack exchange,提问作者johnsmith
相关产品推荐
相关产品推荐

