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

构建三层DNN解决Titanic Dataset时遇targets[3]越界错误求助

Troubleshooting "targets[3] is out of range" in Your Titanic DNN

Hey there! Let's break down that targets[3] is out of range error you're hitting while building your 3-layer DNN for the Titanic Dataset. This is a super common issue with classification models, and it almost always comes down to a mismatch between your model's output setup and your target labels.

Common Causes & Fixes

  • Check your target variable (Survived column) values
    The Titanic survival target should only be 0 (did not survive) or 1 (survived). Run this quick check in your notebook to make sure there are no unexpected values:

    print(df['Survived'].unique())
    

    If you see values like 2 or 3, that's a red flag—you'll need to clean your dataset to remove or correct those entries.

  • Verify your model's final layer configuration
    For binary classification (which this problem is), your output layer needs to match one of these valid setups:

    1. Single neuron with sigmoid activation: Use this when your target is a binary integer (0/1). Example:

      model.add(Dense(1, activation='sigmoid'))
      

      Pair this with the binary_crossentropy loss function.

    2. Two neurons with softmax activation: Use this if you're framing the problem as a 2-class multi-class task. Example:

      model.add(Dense(2, activation='softmax'))
      

      Pair this with sparse_categorical_crossentropy (if targets are integers) or categorical_crossentropy (if targets are one-hot encoded).

      If your final layer has 3+ neurons, your model expects 3+ classes, but your target only has 0/1—this will trigger the "out of range" error when the model tries to map a target label to an output index that doesn't exist.

  • Double-check your loss function alignment
    Mismatching your loss function to the output layer is another frequent culprit. For example:

    • Using categorical_crossentropy without one-hot encoding your target labels will lead to index errors, since this loss expects one-hot vectors instead of raw integer labels.

Give these checks a shot—odds are one of them will fix your error. Feel free to follow up if you hit any roadblocks while debugging!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:32:16