无法解决TypeError: unhashable type: 'numpy.ndarray'错误求助
Hey there! Let's work through this frustrating error you're hitting. That TypeError pops up when you try to use a numpy array in a spot that expects a hashable object—think dictionary keys, set elements, or even some TensorFlow API calls that rely on hashable values under the hood. Let's break down the most common causes and fixes:
Common Scenarios & Fixes
1. You're using a numpy array as a dictionary key or set element
This is the most frequent culprit. Numpy arrays are mutable, so they can't be hashed (a requirement for dictionary keys and set members).
Example of the error:
import numpy as np my_array = np.array([1, 2, 3]) my_dict = {} my_dict[my_array] = "model_weights" # Boom! Error hits here
Fix it by converting the array to a tuple:
Tuples are immutable and hashable, so they work perfectly for this use case:
my_dict[tuple(my_array)] = "model_weights"
2. Incorrect input handling when passing data to TensorFlow
If the error fires while training or running your model, you're probably passing numpy arrays in a wrong format to TensorFlow APIs. For example:
- Accidentally using a numpy array as a key in a dictionary when calling
model.fit() - Passing a nested array structure that TensorFlow can't process without hash checks
Example of the error:
import tensorflow as tf import numpy as np X_train = np.random.rand(100, 10) y_train = np.random.randint(0, 2, size=(100,)) model = tf.keras.Sequential([ tf.keras.layers.Dense(32, activation='relu', input_shape=(10,)), tf.keras.layers.Dense(1, activation='sigmoid') ]) model.compile(optimizer='adam', loss='binary_crossentropy') model.fit({X_train: y_train}, epochs=5) # Wrong! Using X_train as a dict key
Fix it by passing inputs and labels correctly:
TensorFlow expects separate arguments for features and labels (or a tuple if using multiple inputs/outputs):
model.fit(X_train, y_train, epochs=5)
3. Issues with @tf.function and numpy array parameters
If you're using TensorFlow's @tf.function decorator, passing numpy arrays can sometimes trigger hash checks inside the function (especially if you're using them in caches or dictionaries).
Example of the error:
import tensorflow as tf import numpy as np @tf.function def predict_with_cache(input_arr): prediction_cache = {} prediction_cache[input_arr] = model(input_arr) # Error here return prediction_cache[input_arr] predict_with_cache(np.array([0.1, 0.2]))
Fix it by converting the array to a hashable type inside the function:
@tf.function def predict_with_cache(input_arr): prediction_cache = {} # Convert numpy array to a tuple (or use tensor.numpy() if working with tensors) cache_key = tuple(input_arr.numpy()) prediction_cache[cache_key] = model(input_arr) return prediction_cache[cache_key]
Quick Debugging Step
First, look at the full error stack trace—it will tell you exactly which line of code is causing the problem. That's the fastest way to narrow down whether it's a dictionary/set issue, a TensorFlow data passing issue, or something else.
Once you find that line, ask yourself: Am I using this numpy array somewhere that needs a fixed, unchanging value (like a key)? If yes, convert it to a tuple or adjust your logic to avoid using the array in that context.
内容的提问来源于stack exchange,提问作者Taby




