Reputation: 168
term_map
tracks which term is in which position.In [256]: term_map = np.array([2, 2, 3, 4, 4, 4, 2, 0, 0, 0])
In [257]: term_map
Out[257]: array([2, 2, 3, 4, 4, 4, 2, 0, 0, 0])
term_scores
tracks the weight of each term at each position.In [258]: term_scores = np.array([5, 6, 9, 8, 9, 4, 5, 1, 2, 1])
In [259]: term_scores
Out[259]: array([5, 6, 9, 8, 9, 4, 5, 1, 2, 1])
In [260]: unqID, idx = np.unique(term_map, return_inverse=True)
In [261]: unqID
Out[261]: array([0, 2, 3, 4])
In [262]: value_sums = np.bincount(idx, term_scores)
In [263]: value_sums
Out[263]: array([ 4., 16., 9., 21.])
term_map
variable.In [254]: vocab = np.zeros(13)
In [255]: vocab
Out[255]: array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.])
vocab
variable.In [255]: updated_vocab
Out[255]: array([ 4., 0., 16., 9., 21., 0., 0., 0., 0., 0., 0., 0., 0.])
How do I create 6?
Upvotes: 2
Views: 2266
Reputation: 221684
As it turns out, we can avoid the np.unique
step to directly get to the desired output by feeding in term_map
and term_scores
to np.bincount
and also mention the length of the output array with its optional argument minlength
.
Thus, we could simply do -
final_output = np.bincount(term_map, term_scores, minlength=13)
Sample run -
In [142]: term_map = np.array([2, 2, 3, 4, 4, 4, 2, 0, 0, 0])
...: term_scores = np.array([5, 6, 9, 8, 9, 4, 5, 1, 2, 1])
...:
In [143]: np.bincount(term_map, term_scores, minlength=13)
Out[143]:
array([ 4., 0., 16., 9., 21., 0., 0., 0., 0., 0., 0.,
0., 0.])
Upvotes: 3
Reputation: 14863
import numpy as np
term_map = np.array([2, 2, 3, 4, 4, 4, 2, 0, 0, 0])
term_scores = np.array([5, 6, 9, 8, 9, 4, 5, 1, 2, 1])
unqID, idx = np.unique(term_map, return_inverse=True)
value_sums = np.bincount(idx, term_scores)
vocab = np.zeros(13)
vocab[unqID] = value_sums
print(vocab)
OUT: [ 4. 0. 16. 9. 21. 0. 0. 0. 0. 0. 0. 0. 0.]
Upvotes: 2