构建三层DNN解决Titanic Dataset时遇targets[3]越界错误求助
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 (
Survivedcolumn) values
The Titanic survival target should only be0(did not survive) or1(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
2or3, 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: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_crossentropyloss function.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) orcategorical_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_crossentropywithout one-hot encoding your target labels will lead to index errors, since this loss expects one-hot vectors instead of raw integer labels.
- Using
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

