Consider this simple example
data = pd.DataFrame({'text1' : ['hello world', 'hello universe'],
'text2': ['good morning', 'hello two three']})
data
Out[489]:
text1 text2
0 hello world good morning
1 hello universe hello two three
As you can see, text1 and text2 share one exact word in common: hello. I am trying to create ngrams separately for text1 and text2 and I want to concatenate the results together into a countvectorizer object.
The idea is that I want to create ngrams separately for the two variables and used them as features in a ML algo. However, I do want the extra ngrams that would be created by concatenating the string together, like world good in hello world good morning. This is why I keep the ngram creation separated.
The issue is that by doing so, the resulting (sparse) vector will contain a duplicated hello column.
See here:
vector = CountVectorizer(ngram_range=(1, 2))
v1 = vector.fit_transform(data.text1.values)
print(vector.get_feature_names())
['hello', 'hello universe', 'hello world', 'universe', 'world']
v2 = vector.fit_transform(data.text2.values)
print(vector.get_feature_names())
['good', 'good morning', 'hello', 'hello two', 'morning', 'three', 'two', 'two three']
And now concatenating v1 and v2 gives 13 columns
from scipy.sparse import hstack
print(hstack((v1, v2)).toarray())
[[1 0 1 0 1 1 1 0 0 1 0 0 0]
[1 1 0 1 0 0 0 1 1 0 1 1 1]]
The proper text-features should be 12:
hello, word, hello word, good, morning, good morning,hello universe,universe, two, three, hello two, two three
What can I do here to have the proper unique words as features? Thanks!