# The number of dense units for classification

**URL:** <https://root-forum.cern.ch/t/the-number-of-dense-units-for-classification/48898>\
**Category:** TMVA\
**Tags:** python\
**Created:** [February 22, 2022, 1:54am UTC](https://root-forum.cern.ch/t/the-number-of-dense-units-for-classification/48898 "2022-02-22T01:54:41Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![littlepi](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/littlepi/32/23633_2.png) [@littlepi](https://root-forum.cern.ch/u/littlepi)\
**Post date:** [February 22, 2022, 1:54am UTC](https://root-forum.cern.ch/t/the-number-of-dense-units-for-classification/48898/1 "2022-02-22T01:54:41Z")

</div>

Hi,

I have a simple question about classification. For a binary classification, the number of units of the last dense layer should be 1 or 2? In tutorial “TMVA\_RNN\_Classification.C”, the last layer is a dense layer with 2 units (see code below). Why it is not 1? Because you want to have a single probability for both signal and background? I have tried to use 1 instead, the program fails to run. Can someone please guide me about this issue? Thank you in advance.

import keras  
from keras.models import Sequential  
from keras.optimizers import adam\_v2  
from keras.layers import Input, Dense, Dropout, Flatten, SimpleRNN, GRU, LSTM, Reshape, BatchNormalization

model = keras.models.Sequential()  
model.add(Reshape((10, 30), input\_shape = (10\*30, )))  
model.add(LSTM(units=10, return\_sequences=True) )  
model.add(Flatten())  
model.add(Dense(64, activation = ‘tanh’))  
model.add(Dense(2, activation = ‘sigmoid’))  
model.compile(loss = ‘binary\_crossentropy’, optimizer = adam\_v2.Adam(lr = 0.001), metrics = [‘accuracy’])  
modelName = ‘model\_LSTM.h5’  
model.save(modelName)  
model.summary()

---

<div class="post-metadata">

**Author:** ![couet](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/couet/32/12037_2.png) [@couet](https://root-forum.cern.ch/u/couet)\
**Post date:** [February 22, 2022, 7:39am UTC](https://root-forum.cern.ch/t/the-number-of-dense-units-for-classification/48898/2 "2022-02-22T07:39:25Z")

</div>

I think @moneta can help.

---

<div class="post-metadata">

**Author:** ![moneta](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/moneta/32/19423_2.png) [@moneta](https://root-forum.cern.ch/u/moneta)\
**Post date:** [February 23, 2022, 2:11pm UTC](https://root-forum.cern.ch/t/the-number-of-dense-units-for-classification/48898/3 "2022-02-23T14:11:13Z")

</div>

Hi,

You can have 1 unit at the end which will output the probability of the event to be of type signal or 2 units, where the first will give the signal probability and the second one the background probability (= 1 - signal\_prob).  
The model should work also with one. Which error are you having ?

Lorenzo

---

<div class="post-metadata">

**Author:** ![littlepi](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/littlepi/32/23633_2.png) [@littlepi](https://root-forum.cern.ch/u/littlepi)\
**Post date:** [February 24, 2022, 6:21am UTC](https://root-forum.cern.ch/t/the-number-of-dense-units-for-classification/48898/4 "2022-02-24T06:21:07Z")

</div>

Hi moneta,

I simply change the number of units from 2 to 1. The modified code is:  
“model.add(Dense(1, activation = ‘sigmoid’))”

The error messages are listed below:  
 : Failed to run python code: history = model.fit(trainX, trainY, sample\_weight=trainWeights, batch\_size=batchSize, epochs=numEpochs, verbose=verbose, validation\_data=(valX, valY, valWeights), callbacks=callbacks)  
 : Python error message:  
Traceback (most recent call last):  
File “”, line 1, in   
File “/home/guang/.local/lib/python3.6/site-packages/keras/engine/training.py”, line 1184, in fit  
tmp\_logs = self.train\_function(iterator)  
File “/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/eager/def\_function.py”, line 885, in **call**  
result = self.\_call(\*args, \*\*kwds)  
File “/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/eager/def\_function.py”, line 933, in \_call  
self.\_initialize(args, kwds, add\_initializers\_to=initializers)  
File “/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/eager/def\_function.py”, line 760, in \_initialize  
\*args, \*\*kwds))  
File “/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/eager/function.py”, line 3066, in \_get\_concrete\_function\_internal\_garbage\_collected  
graph\_function, \_ = self.\_maybe\_define\_function(args, kwargs)  
File “/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/eager/function.py”, line 3463, in \_maybe\_define\_function  
graph\_function = self.\_create\_graph\_function(args, kwargs)  
File “/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/eager/function.py”, line 3308, in \_create\_graph\_function  
capture\_by\_value=self.\_capture\_by\_value),  
File “/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/framework/func\_graph.py”, line 1007, in func\_graph\_from\_py\_func  
func\_outputs = python\_func(\*func\_args, \*\*func\_kwargs)  
File “/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/eager/def\_function.py”, line 668, in wrapped\_fn  
out = weak\_wrapped\_fn(). **wrapped** (\*args, \*\*kwds)  
File “/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/framework/func\_graph.py”, line 994, in wrapper  
raise e.ag\_error\_metadata.to\_exception(e)  
ValueError: in user code:

```
/home/guang/.local/lib/python3.6/site-packages/keras/engine/training.py:853 train_function *
    return step_function(self, iterator)
/home/guang/.local/lib/python3.6/site-packages/keras/engine/training.py:842 step_function **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/distribute/distribute_lib.py:1286 run
    return self._extended.call_for_each_replica(fn, args=args, kwargs=kwargs)
/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/distribute/distribute_lib.py:2849 call_for_each_replica
    return self._call_for_each_replica(fn, args, kwargs)
/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/distribute/distribute_lib.py:3632 _call_for_each_replica
    return fn(*args, **kwargs)
/home/guang/.local/lib/python3.6/site-packages/keras/engine/training.py:835 run_step **
    outputs = model.train_step(data)
/home/guang/.local/lib/python3.6/site-packages/keras/engine/training.py:789 train_step
    y, y_pred, sample_weight, regularization_losses=self.losses)
/home/guang/.local/lib/python3.6/site-packages/keras/engine/compile_utils.py:201 __call__
    loss_value = loss_obj(y_t, y_p, sample_weight=sw)
/home/guang/.local/lib/python3.6/site-packages/keras/losses.py:141 __call__
    losses = call_fn(y_true, y_pred)
/home/guang/.local/lib/python3.6/site-packages/keras/losses.py:245 call **
    return ag_fn(y_true, y_pred, **self._fn_kwargs)
/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/util/dispatch.py:206 wrapper
    return target(*args, **kwargs)
/home/guang/.local/lib/python3.6/site-packages/keras/losses.py:1809 binary_crossentropy
    backend.binary_crossentropy(y_true, y_pred, from_logits=from_logits),
/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/util/dispatch.py:206 wrapper
    return target(*args, **kwargs)
/home/guang/.local/lib/python3.6/site-packages/keras/backend.py:5000 binary_crossentropy
    return tf.nn.sigmoid_cross_entropy_with_logits(labels=target, logits=output)
/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/util/dispatch.py:206 wrapper
    return target(*args, **kwargs)
/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/ops/nn_impl.py:246 sigmoid_cross_entropy_with_logits_v2
    logits=logits, labels=labels, name=name)
/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/util/dispatch.py:206 wrapper
    return target(*args, **kwargs)
/home/guang/.local/lib/python3.6/site-packages/tensorflow/python/ops/nn_impl.py:133 sigmoid_cross_entropy_with_logits
    (logits.get_shape(), labels.get_shape()))

ValueError: logits and labels must have the same shape ((100, 1) vs (100, 2))

```

: Failed to train model  
\*\*\*\> abort program execution  
terminate called after throwing an instance of ‘std::runtime\_error’  
what(): FATAL error

---

<div class="post-metadata">

**Author:** ![moneta](https://root-forum.cern.ch/user_avatar/root-forum.cern.ch/moneta/32/19423_2.png) [@moneta](https://root-forum.cern.ch/u/moneta)\
**Post date:** [February 24, 2022, 8:30am UTC](https://root-forum.cern.ch/t/the-number-of-dense-units-for-classification/48898/5 "2022-02-24T08:30:07Z")

</div>

Hello,  
Thank you for reporting the error.  
It is correct, the TMVA Keras creates internally an array of labels that is used for training and it has the shape (number of events, number of classes), therefore you would need to have two output units for binary classification. It can work with one output unit, but you would need to have the corrrect label array.  
So it will work if you use directly Keras, but not in the TMVA interface.  
If this for you it is important, to have only one output unit in binary classification, I could try to fix this error.

Best regards

Lorenzo
