# Solve for classification threshold in batch

**URL:** <https://discuss.pytorch.org/t/solve-for-classification-threshold-in-batch/33886>\
**Category:** autograd\
**Created:** [January 5, 2019, 8:26pm UTC](https://discuss.pytorch.org/t/solve-for-classification-threshold-in-batch/33886 "2019-01-05T20:26:37Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![GdMacmillan](https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/gdmacmillan/32/12284_2.png) [@GdMacmillan](https://discuss.pytorch.org/u/GdMacmillan)\
**Post date:** [January 5, 2019, 8:26pm UTC](https://discuss.pytorch.org/t/solve-for-classification-threshold-in-batch/33886/1 "2019-01-05T20:26:37Z")

</div>

Hi, I’m trying to do the following. I have a net, with pre-trained weights. For each mini-batch i have some gold standard labels i want to compare to the scores output from the net and then a sigmoid function. within this mini-batch I want to create a for loop in which I optimize `params` to achieve best f1 metric. Currently, I am trying to compute grads with respect to `f1_loss` for one step. It fails at loss.backward()

```auto
net.eval()
data = next(iter(trainLoader))
inputs, labels = data['image'], data['labels']
outputs = net(inputs)

params = torch.ones((2,)).new_full((28,), .5, requires_grad=True)

scores = torch.sigmoid(outputs)
preds = scores.data.gt(params)
loss = f1_loss(preds, labels) # tensor(0.4878)

loss.backward()

```

throws an error:

* * *

RuntimeError Traceback (most recent call last)  
 in   
----\> 1 loss.backward()

~/anaconda3/envs/k-protein/lib/python3.7/site-packages/torch/tensor.py in backward(self, gradient, retain\_graph, create\_graph)  
91 products. Defaults to `False`.  
92 “”"  
—\> 93 torch.autograd.backward(self, gradient, retain\_graph, create\_graph)  
94  
95 def register\_hook(self, hook):

~/anaconda3/envs/k-protein/lib/python3.7/site-packages/torch/autograd/ **init**.py in backward(tensors, grad\_tensors, retain\_graph, create\_graph, grad\_variables)  
88 Variable.\_execution\_engine.run\_backward(  
89 tensors, grad\_tensors, retain\_graph, create\_graph,  
—\> 90 allow\_unreachable=True) # allow\_unreachable flag  
91  
92

RuntimeError: element 0 of tensors does not require grad and does not have a grad\_fn

Params is the correct size, i.e. a 28 element tensor to be broadcast along the row dimension of the preds tensor which is (batch size, 28).

Types:

`preds.type()`  
‘torch.ByteTensor’

`loss.type()`  
‘torch.FloatTensor’
