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

Jupyter Notebook中KeyError排查与Fruit360代码报错求助

Hey there, let's break down your problem and fix it step by step!

1. Why You're Getting This KeyError

The error message clearly points out that the string 'C:\Users\Msi\Desktop\KaggleDataset\fruits-360_dataset\fruits-360\Test\Apple Braeburn' isn’t a key in your label_to_id_dict.

Chances are, your label_to_id_dict uses fruit category names (like "Apple Braeburn") as keys, but your Test_labels list contains full folder paths instead. When you try to look up the full path in the dictionary, it can’t find a match—hence the KeyError.

2. Fix for Your Fruit360 Specific Issue

Here’s how to adjust your code to align with the dictionary’s keys:

Step 1: Extract the Fruit Category Name from the Path

Use Python’s os.path.basename() to pull just the folder name (which is the fruit category) from each path in Test_labels:

import os
# Clean up Test_labels to get only the fruit category name
Test_labels_cleaned = [os.path.basename(x) for x in Test_labels]
# Now convert to IDs using the cleaned labels
Test_label_ids = np.array([label_to_id_dict[x] for x in Test_labels_cleaned])

Step 2: Verify Matching Formats

If you still get an error, check that the cleaned labels match the dictionary’s key format exactly (case, spaces, underscores all matter!). Print a few examples to compare:

# Print first 5 keys from your dictionary to check format
print(list(label_to_id_dict.keys())[:5])
# Print first 5 cleaned labels to match
print(Test_labels_cleaned[:5])

If there’s a mismatch (e.g., dictionary uses "apple_braeburn" but your cleaned label is "Apple Braeburn"), standardize both:

# Standardize cleaned labels: lowercase + replace spaces with underscores
Test_labels_cleaned = [os.path.basename(x).lower().replace(" ", "_") for x in Test_labels]
# Update the dictionary to match the same format
label_to_id_dict = {k.lower().replace(" ", "_"): v for k, v in label_to_id_dict.items()}
3. General Tips to Fix KeyError in Jupyter Notebook

Beyond this specific case, here are go-to steps for debugging KeyErrors in Jupyter:

  • Find exactly which keys are missing: Before running the line that errors, print out elements in your list that aren’t in the dictionary:
    missing_keys = [x for x in Test_labels if x not in label_to_id_dict]
    print("Missing keys (first 10):", missing_keys[:10])
    
  • Check for hidden characters or data type mismatches: Use repr() to see the raw string (including hidden spaces/newlines) and confirm data types:
    # Inspect the first missing key's raw representation
    print(repr(missing_keys[0]))
    # Check if the key and dictionary keys are the same type
    print(type(missing_keys[0]), type(list(label_to_id_dict.keys())[0]))
    
  • Use dict.get() to avoid crashes (temporarily): If you need to bypass errors to debug further, use get() to return a default value for missing keys:
    # Return -1 for any missing key (adjust default as needed)
    Test_label_ids = np.array([label_to_id_dict.get(x, -1) for x in Test_labels])
    # Then find which indices have invalid IDs
    invalid_indices = np.where(Test_label_ids == -1)[0]
    print("Invalid label indices (first 10):", invalid_indices[:10])
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 12:07:29