Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list notation, Numpy array notation: predictions[predictions < 1e-10] = 1e-10

I am trying to find out operation applied on list. I have list/array name predictions and and executing following set of instruction.

predictions[predictions < 1e-10] = 1e-10

This code snippet is from a Udacity Machine Learning assignment that uses Numpy.

It was used in the following manner:

def logprob(predictions, labels):
    """Log-probability of the true labels in a predicted batch."""
    predictions[predictions < 1e-10] = 1e-10
    return np.sum(np.multiply(labels, -np.log(predictions))) / labels.shape[0]

As pointed out by @MosesKoledoye and various others, it is actually a Numpy array. (Numpy is a Python library)

What does this line do?

like image 692
Taivanbat Badamdorj Avatar asked Jul 25 '16 08:07

Taivanbat Badamdorj


People also ask

How do I check if an array is 1D or 2D in Python?

Look for array. shape: if it comes like (2,) means digit at first place but nothing after after comma,its 1D. Else if it comes like (2,10) means two digits with comma,its 2D.

How do I get rid of NumPy in scientific notation?

Use numpy. set_printoptions() to print an array without scientific notation. Call set_printoptions(suppress=True) to suppress scientific notation when printing.

What is NumPy array in Python?

A numpy array is a grid of values, all of the same type, and is indexed by a tuple of nonnegative integers. The number of dimensions is the rank of the array; the shape of an array is a tuple of integers giving the size of the array along each dimension.


2 Answers

As pointed out by @MosesKoledoye, predictions is most likely a numpy array.

A boolean array would then be generated using predictions < 1e-10. At all indices where the boolean array set by the condition is True, the value will be changed to 1e-10, ie. 10-10.

Example:

  >>> a = np.array([1,2,3,4,5]) #define array
  >>> a < 3 #define boolean array through condition
  array([ True,  True, False, False, False], dtype=bool)

  >>> a[a<3]  #select elements using boolean array
  array([1, 2])

  >>> a[a<3] = -1  #change value of elements which fit condition
  >>> a 
  array([-1, -1,  3,  4,  5])

The reason this might be done in the code could be to prevent division by zero or to prevent negative numbers messing up things by instead inserting a very small number.

like image 168
M.T Avatar answered Nov 03 '22 00:11

M.T


All elements of the array, for which the condition (element < 1e-10) is true, are set to 1e-10. Practically you are setting a minimum value.

like image 23
Nikolas Rieble Avatar answered Nov 02 '22 23:11

Nikolas Rieble