train = np.zeros([26,26])
train2 = np.zeros([26,26])
tmp = [1,2,3,4,5,6,1,2,3,4,5,6]
train[tmp[0:-1], tmp[1:]] += 1
for i in range(len(tmp)-1):
train2[tmp[i], tmp[i+1]] += 1
print(np.sum(train - train2))
the output is -5
I find that train
is not equal to train2
when there are some duplicate tuples in tmp
. Is there something wrong in numpy slicing.
The same to you.
You know that you're trying to write to the "same position" twice, for example [1, 2]
. Unfortunatly (or fortunatly, depending on the point of view) that doesn't work.
But you can use np.add.at
which according to the docs "For addition ufunc, this method is equivalent to a[indices] += b, except that results are accumulated for elements that are indexed more than once.":
train = np.zeros([26,26])
np.add.at(train, [tmp[:-1], tmp[1:]], 1)
Thanks!
Most helpful comment
You know that you're trying to write to the "same position" twice, for example
[1, 2]
. Unfortunatly (or fortunatly, depending on the point of view) that doesn't work.But you can use
np.add.at
which according to the docs "For addition ufunc, this method is equivalent to a[indices] += b, except that results are accumulated for elements that are indexed more than once.":