Python collections and numpy arrays - Mon, Nov 21, 2022
Python collections and numpy arrays
While working through the source code of the book AI and Machine Learning for Coders I stumbled across the following lines, in which a test data set is loaded using the TensorFlow API :
(training_images, training_labels), (test_images, test_labels) = data.load_data()
training_images = training_images / 255.0
The first thing I pondered upon was the return type of the method data.load_data()
because of python’s dynamic typing. Here is an explanation of what is returned:
The method returns two tuples
. The type of all the tuple values is a numpy array
The type of the tuple elements could only be determined during running the code or looking at the documentation respectively.
Knowing the type of the tuple elements explains why the line training_images = training_images / 255.0
works. The /
operator is applied to all elements in the numpy array:
numbers_as_numpy_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
print(numbers_as_numpy_array / 2) # prints [0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. ]
Based on this understanding I made a small gist that shows the different types of collections and numpy arrays.