Categorical to Numerical labels

Hey Everyone, I’m returning to pytorch since a while, and i’m tackling a multi class classification problem for categorical data.
I have 18 categorical labels(names of countries) and I’m trying to convert them to one hot labels?
I’m now Using the sklearn class (LabelEncoder) but this method is just converting categories to numbers, and i want to one hot encode them?
Any method to do this in pytorch?
Please note that i have Train and val in two separate csv files.

Thank you so much for your help

You could use F.one_hot to create one-hot encoded targets from target tensors containing class indices.
Note however, that built-in loss functions for multi-class classification use cases (e.g. nn.CrossEntropyLoss and nn.NLLLoss) expect targets containing class indices and not one-hot encoded targets (in newer versions nn.CrossEntropyLoss would accept these and would treat them as probabilities).

1 Like