Future
Future

Reputation: 219

'float' object has no attribute 'round'

I have a code was shown below:

history['test_acc'].append(results.history['val_dense_5_accuracy'][0]) 

then I want to print like below:

 print('Epoch: '+str(epoch)+'/'+str(epochs-1), 'Learning rate:', 
      'Test_acc:', history['test_acc'][-1].round(4),
      'Test_loss:', history['test_loss'][-1].round(4))`

but in this this line:

'Test_acc:', history['test_acc'][-1].round(4)

i have this error: 'float' object has no attribute 'round' what's the problem?

Upvotes: 21

Views: 48060

Answers (2)

Poe Dator
Poe Dator

Reputation: 4903

Here is the likely source of confusion in this matter: The .round() method works with numpy.floatXX objects, which may look like floats but have some extra methods. If not certain in the object type - use round() function.

demo:

>>> import numpy as np
>>> a = np.random.rand(5)
>>> a
array([0.92254859, 0.37214161, 0.35441334, 0.14139935, 0.40351668])
>>> z = a.mean()
>>> type(z)
<class 'numpy.float64'>
>>> z
0.43880391309677796
>>> z.round(3)   # works OK with np.float64
0.439

>>> b = 2.345
>>> b.round(1)   # fails with regular float
AttributeError: 'float' object has no attribute 'round'
>>> type(b)
<class 'float'>
 

Upvotes: 1

ShadowRanger
ShadowRanger

Reputation: 155438

The problem is that round is a built-in top level function, not a method on floats. Change:

history['test_acc'][-1].round(4)

to:

round(history['test_acc'][-1], 4) 

with a similar change to the test_loss expression.

Upvotes: 42

Related Questions