You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow训练神经网络报错:TypeError(Series对象不可哈希)及代码排查

Fixing TypeError: 'Series' objects are mutable, thus they cannot be hashed in TensorFlow Training

Hey there! Let's break down why this error is popping up and how to fix it, even after you've converted your target features to integers.

What's Causing This Error?

Pandas Series are mutable objects (you can tweak their values after creating them), and Python blocks mutable objects from being used as hash keys. TensorFlow runs into this issue when it tries to hash feature identifiers—like when defining feature columns, mapping features in a dataset, or linking input layers to your data. Even if you've converted the Series values to integers, passing the Series object itself to TensorFlow will trigger this error.

Common Mistakes to Check (and Fixes)

Let's walk through the most likely issues in your code, with before/after examples:

1. Using a Series Instead of a Column Name String for Feature Columns

It's easy to accidentally pass df['target'] (a Series) to TensorFlow's feature column functions instead of the column name as a string.

Wrong Code:

# ❌ Passing the Series directly to the feature column
target_col = tf.feature_column.categorical_column_with_vocabulary_list(
    df['target'],  # This is a Series, not a string
    vocabulary_list=[0, 1, 2]
)

Fixed Code:

# ✅ Pass the column name as a string, use the Series only to get vocab values
df['target'] = df['target'].astype(int)  # Your existing conversion step

target_col = tf.feature_column.categorical_column_with_vocabulary_list(
    'target',  # Column name string here
    vocabulary_list=df['target'].unique().tolist()  # Use Series to get vocab
)

2. Passing Series to tf.data.Dataset Instead of Numpy Arrays

When building your dataset, TensorFlow expects dictionary keys to be strings, and values to be immutable arrays (not Series).

Wrong Code:

# ❌ Using Series directly in the dataset
labels = df['target']
ds = tf.data.Dataset.from_tensor_slices((dict(df), labels))  # labels is a Series

Fixed Code:

# ✅ Convert Series to numpy arrays with .values or .to_numpy()
df['target'] = df['target'].astype(int)

labels = df.pop('target').values  # Convert to numpy array
ds = tf.data.Dataset.from_tensor_slices((dict(df), labels))

3. Full Working Example

Here's a complete, corrected implementation that avoids the hashing error:

import pandas as pd
import tensorflow as tf

# Load and preprocess data (convert features to integers upfront)
df = pd.read_csv('your_dataset.csv')
df['target'] = df['target'].astype(int)
df['feature_1'] = df['feature_1'].astype(int)
df['feature_2'] = df['feature_2'].astype(int)

# Define feature columns using column names (not Series)
target_cat_col = tf.feature_column.categorical_column_with_vocabulary_list(
    'target',
    vocabulary_list=df['target'].unique().tolist()
)
target_encoded = tf.feature_column.indicator_column(target_cat_col)

feature_1_col = tf.feature_column.numeric_column('feature_1')
feature_2_col = tf.feature_column.numeric_column('feature_2')

all_feature_cols = [target_encoded, feature_1_col, feature_2_col]

# Build dataset with numpy arrays instead of Series
def create_dataset(dataframe, batch_size=32, shuffle=True):
    dataframe = dataframe.copy()
    labels = dataframe.pop('target').values  # Convert to numpy array
    ds = tf.data.Dataset.from_tensor_slices((dict(dataframe), labels))
    if shuffle:
        ds = ds.shuffle(buffer_size=len(dataframe))
    return ds.batch(batch_size)

train_ds = create_dataset(df)

# Build and train the model
model = tf.keras.Sequential([
    tf.keras.layers.DenseFeatures(all_feature_cols),
    tf.keras.layers.Dense(64, activation='relu'),
    tf.keras.layers.Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
model.fit(train_ds, epochs=10)

Quick Checklist to Debug Your Code

  • Double-check every TensorFlow API call that references your data: ensure you're passing column name strings instead of Series objects.
  • When creating datasets or labels, convert all Series to numpy arrays with .values or .to_numpy().
  • Verify that any dictionary keys used with TensorFlow are immutable (strings, integers)—never a Series.

内容的提问来源于stack exchange,提问作者User

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 06:30:29