使用sklearn和pandas在一个模型中组合单词和其他功能

Jer*_*emy 19 python nlp machine-learning pandas scikit-learn

我试图根据帖子的文本和其他功能(一天中的时间,帖子的长度等)来模拟帖子收到的分数.

我想知道如何最好地将这些不同类型的功能组合到一个模型中.现在,我有类似以下内容(从这里这里被盗).

import pandas as pd
...

def features(p):
    terms = vectorizer(p[0])
    d = {'feature_1': p[1], 'feature_2': p[2]}
    for t in terms:
        d[t] = d.get(t, 0) + 1
    return d

posts = pd.read_csv('path/to/csv')

# Create vectorizer for function to use
vectorizer = CountVectorizer(binary=True, ngram_range=(1, 2)).build_tokenizer()
y = posts["score"].values.astype(np.float32) 
vect = DictVectorizer()

# This is the part I want to fix
temp = zip(list(posts.message), list(posts.feature_1), list(posts.feature_2))
tokenized = map(lambda x: features(x), temp)
X = vect.fit_transform(tokenized)
Run Code Online (Sandbox Code Playgroud)

从pandas数据框中提取我想要的所有功能似乎非常愚蠢,只是将它们全部压缩在一起.有没有更好的方法来做这一步?

CSV看起来如下所示:

ID,message,feature_1,feature_2
1,'This is the text',4,7
2,'This is more text',3,2
...
Run Code Online (Sandbox Code Playgroud)

kha*_*mel 22

您可以使用地图和lambda完成所有操作:

tokenized=map(lambda msg, ft1, ft2: features([msg,ft1,ft2]), posts.message,posts.feature_1, posts.feature_2)
Run Code Online (Sandbox Code Playgroud)

这可以节省您的临时临时步骤并迭代3列.

另一个解决方案是将消息转换为CountVectorizer稀疏矩阵,并将此矩阵与posts数据帧中的特征值连接起来(这会跳过必须构造dict并生成类似于DictVectorizer所获得的稀疏矩阵):

import scipy as sp
posts = pd.read_csv('post.csv')

# Create vectorizer for function to use
vectorizer = CountVectorizer(binary=True, ngram_range=(1, 2))
y = posts["score"].values.astype(np.float32) 

X = sp.sparse.hstack((vectorizer.fit_transform(posts.message),posts[['feature_1','feature_2']].values),format='csr')
X_columns=vectorizer.get_feature_names()+posts[['feature_1','feature_2']].columns.tolist()


posts
Out[38]: 
   ID              message  feature_1  feature_2  score
0   1   'This is the text'          4          7     10
1   2  'This is more text'          3          2      9
2   3   'More random text'          3          2      9

X_columns
Out[39]: 
[u'is',
 u'is more',
 u'is the',
 u'more',
 u'more random',
 u'more text',
 u'random',
 u'random text',
 u'text',
 u'the',
 u'the text',
 u'this',
 u'this is',
 'feature_1',
 'feature_2']

X.toarray()
Out[40]: 
array([[1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 4, 7],
       [1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 3, 2],
       [0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 3, 2]])
Run Code Online (Sandbox Code Playgroud)

此外,sklearn-pandas还有DataFrameMapper,可以满足您的需求:

from sklearn_pandas import DataFrameMapper
mapper = DataFrameMapper([
    (['feature_1', 'feature_2'], None),
    ('message',CountVectorizer(binary=True, ngram_range=(1, 2)))
])
X=mapper.fit_transform(posts)

X
Out[71]: 
array([[4, 7, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1],
       [3, 2, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1],
       [3, 2, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0]])
Run Code Online (Sandbox Code Playgroud)

注意:使用最后一种方法时X不稀疏.

X_columns=mapper.features[0][0]+mapper.features[1][1].get_feature_names()

X_columns
Out[76]: 
['feature_1',
 'feature_2',
 u'is',
 u'is more',
 u'is the',
 u'more',
 u'more random',
 u'more text',
 u'random',
 u'random text',
 u'text',
 u'the',
 u'the text',
 u'this',
 u'this is']
Run Code Online (Sandbox Code Playgroud)