我用python编写了一个tweets分类器,然后以.pkl格式保存在磁盘上,这样我就可以一次又一次地运行它,而不必每次都训练它。这是代码:

import pandas
import re
from sklearn.feature_extraction import FeatureHasher

from sklearn.feature_selection import SelectKBest
from sklearn.feature_selection import chi2

from sklearn import cross_validation

from sklearn.externals import joblib


#read the dataset of tweets

header_row=['sentiment','tweetid','date','query', 'user', 'text']
train = pandas.read_csv("training.data.csv",names=header_row)

#keep only the right columns

train = train[["sentiment","text"]]

#remove puctuation, special characters, numbers and lower case the text

def remove_spch(text):

    return re.sub("[^a-z]", ' ', text.lower())

train['text'] = train['text'].apply(remove_spch)


#Feature Hashing

def tokens(doc):
    """Extract tokens from doc.

    This uses a simple regex to break strings into tokens.
    """
    return (tok.lower() for tok in re.findall(r"\w+", doc))

n_features = 2**18
hasher = FeatureHasher(n_features=n_features, input_type="string", non_negative=True)
X = hasher.transform(tokens(d) for d in train['text'])

y = train['sentiment']

X_new = SelectKBest(chi2, k=20000).fit_transform(X, y)

a_train, a_test, b_train, b_test = cross_validation.train_test_split(X_new, y, test_size=0.2, random_state=42)

from sklearn.ensemble import RandomForestClassifier

classifier=RandomForestClassifier(n_estimators=10)
classifier.fit(a_train.toarray(), b_train)
prediction = classifier.predict(a_test.toarray())

#Export the trained model to load it in another project

joblib.dump(classifier, 'my_model.pkl', compress=9)

假设我有另一个Python文件,我想对Tweet进行分类如何进行分类?
from sklearn.externals import joblib
model_clone = joblib.load('my_model.pkl')

mytweet = 'Uh wow:@medium is doing a crowdsourced data-driven investigation tracking down a disappeared refugee boat'

hasher.transform为止,我可以复制相同的过程将其添加到预测模型中,但随后我遇到了无法计算最佳20k特征的问题要使用selectkbest,需要同时添加功能和标签。因为,我想预测标签,所以不能使用selectkbest。那么,我怎样才能通过这个问题继续预测呢?

最佳答案

我支持@EdChum的评论
您可以通过在数据上对它进行培训来构建一个模型,这些数据可能足以代表它处理不可见的数据。
实际上,这意味着您只需要使用FeatureHasherSelectKBestpredict应用于您的新数据。(在新数据上重新训练featurehasher是错误的,因为通常它会产生不同的特性)。
也要这么做
分别腌制FeatureHasherSelectKBest
或者(更好)
对FeatureHasher进行Pipeline操作,选择kbest,然后RandomForestClassifier并对整个管道进行pickle操作然后可以加载此管道并对新数据使用predict

09-25 17:43
查看更多