Ogurchik
Ogurchik

Reputation: 75

Index in numpy's array

Now I'm reading the book "Grokking Deep Learning" and I've encountered a piece that I could to understant

import sys, numpy as np
from keras.datasets import mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
images, labels = (x_train[0:1000].reshape(1000,28*28) \
                                        255, y_train[0:1000])
one_hot_labels = np.zeros((len(labels),10))
for i,l in enumerate(labels):
    one_hot_labels[i][l] = 1 // this row i can't understant
labels = one_hot_labels

How the index l in the arrive one_hot_labels can be array by own? Might that is basic Python but I can't get it

Upvotes: 0

Views: 138

Answers (2)

hpaulj
hpaulj

Reputation: 231665

Make a 2d array:

In [96]: x = np.arange(12).reshape(3,4)
In [97]: x
Out[97]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

Index it with a scalar, given a 1d array, the values of row 1

In [98]: x[1]
Out[98]: array([4, 5, 6, 7])

Index again to get an element

In [99]: x[1][2]
Out[99]: 6

That element can be set in the original array:

In [100]: x[1][2]=0
In [101]: x
Out[101]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  0,  7],
       [ 8,  9, 10, 11]])

However for multidimensional indexing this syntax is better:

In [102]: x[1,2]
Out[102]: 0

Numpy indexing is a big topic, but important.

https://numpy.org/doc/stable/reference/arrays.indexing.html

Upvotes: 1

dominik-air
dominik-air

Reputation: 79

The line one_hot_labels = np.zeros((len(labels),10)) creates an len(labels) by 10 matrix filled with zeroes. It can be compared to a list of lists. That is one_hot_labels is a list of rows and every row is a list of numbers(in this case every number is 0). That's why one_hot_labels[i] is an array on his own. You could try to print(one_hot_labels) to see how it's constructed.

Upvotes: 1

Related Questions