# Weight parameter in nn.CrossEntropyLoss

1. If the accuracy for each class of my model is [0.7, 0.8, 0.2], can I improve the performance of the last class by applying the weight as [1,1,2] in cross-entropy ?

2. When I applied the weight as [1,1,2], I thought the loss would be different from that of ces1. But it gives the same value. Why is that?

``````ces1 = nn.CrossEntropyLoss(reduction='none')

class_weights = [1,1,2]
class_weights = torch.FloatTensor(class_weights).cuda()
ces2 = nn.CrossEntropyLoss(weight=class_weights, reduction='none')
Compute with ces1 : [0.3, 0.4, 0.4]
Compute with ces2 : [0.3, 0.4, 0.4]
``````
1. The weighting should balance the losses and might thus also balance the accuracy. I.e. while the class2 accuracy might increase the other two might decrease.

2. Your current target might not use the class2 index. This code shows the difference:

``````class_weights = torch.tensor([1., 1., 2.])
ces1 = nn.CrossEntropyLoss(reduction='none')
ces2 = nn.CrossEntropyLoss(weight=class_weights, reduction='none')

x = torch.randn(2, 3)
target = torch.tensor([0, 2])

loss1 = ces1(x, target)
> tensor([0.2583, 0.1567])
loss2 = ces2(x, target)
> tensor([0.2583, 0.3133])
``````
1 Like
{"ft_lang_label":"__label__en","ft_lang_prob":0.800233,"math_prob":0.9949456,"size":1148,"snap":"2023-14-2023-23","text_gpt3_token_len":350,"char_repetition_ratio":0.13723776,"word_repetition_ratio":0.0,"special_character_ratio":0.33449477,"punctuation_ratio":0.23828125,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9974514,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-03-24T09:47:07Z\",\"WARC-Record-ID\":\"<urn:uuid:749d1a43-9c6d-4b7e-b541-0685f99fc257>\",\"Content-Length\":\"17479\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:044c3cb5-add1-4e12-aea4-1f714f39881d>\",\"WARC-Concurrent-To\":\"<urn:uuid:52c5c830-a68a-4ef9-8c10-1ea36f5ed9e8>\",\"WARC-IP-Address\":\"159.203.145.104\",\"WARC-Target-URI\":\"https://discuss.pytorch.org/t/weight-parameter-in-nn-crossentropyloss/105109\",\"WARC-Payload-Digest\":\"sha1:AMERYO3JF2GYHJ3WOA4CWN7HAK3BC7FX\",\"WARC-Block-Digest\":\"sha1:D5KOLITRDAJJPRYSXGICNWJJHNSOQDSQ\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-14/CC-MAIN-2023-14_segments_1679296945279.63_warc_CC-MAIN-20230324082226-20230324112226-00512.warc.gz\"}"}