0

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

asked Nov 8, 2020 at 21:19

2 Answers 2

1

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.

answered Nov 8, 2020 at 21:35
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. How I got it the one_hot_labels is just copy the labels?
1

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

answered Nov 9, 2020 at 7:26

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.