Skip to content Skip to sidebar Skip to footer

Don't Understand How This Example One-hot Code Indexes A Numpy Array With [i,j] When J Is A Tuple?

I don't get how the line: results[i, sequence] = 1 works in the following. I am following along in the debugger with some sample code in a Manning book: 'Deep Learning with Python'

Solution 1:

Assuming sequence is a list of integers,

results[i,sequence] = 1

is equivalent to

for j in sequence:
    results[i][j] = 1

Solution 2:

So I am going to make a few assumptions because you did not provide an example of sequences or dimension. I am assuming dimension is the highest possible value + 1 in sequences and each value in sequences is either an integer or a tuple of integers.

This goes through each sequence, and sets all the values in the i'th row to 1.0 where the indicies are in sequence.

# Create an all-zero matrix of shape (len(sequences), dimension)
results = np.zeros((len(sequences), dimension))
for i, sequence inenumerate(sequences):
    results[i, sequence] = 1.# How does this work?return results

So walking through it with these inputs:

import numpy as np
sequences = [(2, 3), (2, 1), 4]
dimension = 5# max value is 4, +1 is 5
results = np.zeros((len(sequences), dimension))
print(results)
#[[0. 0. 0. 0. 0.]# [0. 0. 0. 0. 0.]# [0. 0. 0. 0. 0.]]for i, sequence inenumerate(sequences):
     results[i, sequence] = 1.0print(results)
#[[0. 0. 1. 1. 0.]# [0. 1. 1. 0. 0.]# [0. 0. 0. 0. 1.]]

For the first sequence (2, 3) it replaced the 3rd and 4th items in the array with 1.0

For the second sequence (1, 2) it replaced the 2nd and 3rd items in the array with 1.0

For the last sequence 4 replaced the 5th item with 1.0

Solution 3:

I had the same problem before, then I found it's because results is a numpy array not a list. So within a numpy array you could update it by results[i,sequence] = 1, where sequence is a list of index. But within a list you couldn't do it.

Post a Comment for "Don't Understand How This Example One-hot Code Indexes A Numpy Array With [i,j] When J Is A Tuple?"