简体   繁体   中英

Why do I need to use np.array to not get the error 'list object has no attribute shape'?

import numpy as np
passed_exam = np.array([[0],[0],[0],[0],[0],[0],[0],[0],[0],[1],[1],[0],[0],[1],[1],[1],[1],[1],[1],[1]])
probabilities = np.array([[0.14663296],[0.17444128],[0.20624873],[0.24215472],[0.28209011],[0.32578035],[0.37272418],[0.42219656],[0.47328102],[0.52493108],[0.57605318],[0.62559776],[0.67264265],[0.71645543],[0.7565269 ],[0.79257487],[0.82452363],[0.85246747],[0.87662721],[0.89730719]])
probabilities_2 = np.array([0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5])

def log_loss(probabilities,actual_class):
  return np.sum(-(1/actual_class.shape[0])*(actual_class*np.log(probabilities) + (1-actual_class)*np.log(1-probabilities)))
# shape is a tuple that gives you an indication of the number of dimensions in the array. 
# So in your case, since the index value of Y. shape[0] is 0, 
# you are working along the first dimension of your array

loss_1 = log_loss(probabilities, passed_exam)
print(loss_1)

Before I changed the lists above to np.array , I kept getting the error 'list object has no attribute shape'

Do you know why I need to use np.array to avoid this error?

shape is a method that is available only for numpy ndarrays. An ndarray is different to a default python list , which is what is returned when you initialize with list = [1,2,3] .

The built-in lists do not have a shape, they are just lists inside lists. As a result, they do not store what's inside them, only a reference. Numpy arrays do store the shape though.

Arrays in Numpy have shapes because is it the defined attribute in the numpy package for arrays. The main reason behind it is, arrays are always rectangular, meaning they have same number of items in any dimension. Example:

a = np.arange(6).reshape((2,3))
#[[0 1 2]
# [3 4 5]]

The shape of this is a.shape = (2,3) . In numpy you cannot have an array like this:

#This does not exist in numpy
#[[0 1]
# [3 4 5]]

simply because it is not rectangular.

Now, as for lists, you can have such a list:

l = [[0, 1], [3, 4, 5]]

because lists can have non-rectangular shapes, therefore, they did not have a shape attribute defined for them. Instead, they only have a function len to count the number of elements in them:

len(l)
#2

If you know your list is rectangular and want a shape, use this to convert it to an array:

import numpy as np
a = np.array(l)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM