2016-05-06 16 views
0

メール(スパム/スパムではない)データセットにガウス型Naive Bayes分類子を作成し、正常に実行できました。私はデータをベクトル化し、列車とテストセットに分けて、Sklearn-Gaussian Naive Bayesクラシファイアに存在するすべての機能を正確に計算しました。彼らがスパムであるか否か -sklearnの訓練されたNBクラシファイアを使用してメールのラベルを予測する方法は?

今、私は、新しい電子メールを「ラベル」を予測するために、この分類器を使用することができるようにしたいです。 たとえば、電子メールがあるとします。私はそれを自分のクラシファイアにフィードし、それが迷惑メールかどうかの予測を得たいと思う。どうすればこれを達成できますか?助けてください。

クラシファイアファイルのコード。ベクトル化のための

#!/usr/bin/python 
 

 
import sys 
 
from time import time 
 
import logging 
 

 
# Display progress logs on stdout 
 
logging.basicConfig(level = logging.DEBUG, format = '%(asctime)s %(message)s') 
 

 
sys.path.append("../DatasetProcessing/") 
 
from vectorize_split_dataset import preprocess 
 

 
### features_train and features_test are the features 
 
for the training and testing datasets, respectively### labels_train and labels_test are the corresponding item labels 
 
features_train, features_test, labels_train, labels_test = preprocess() 
 

 
######################################################### 
 
from sklearn.naive_bayes import GaussianNB 
 
clf = GaussianNB() 
 
t0 = time() 
 
clf.fit(features_train, labels_train) 
 
pred = clf.predict(features_test) 
 
print("training time:", round(time() - t0, 3), "s") 
 
print(clf.score(features_test, labels_test)) 
 

 
## Printing Metrics 
 
for Training and Testing 
 
print("No. of Testing Features:" + str(len(features_test))) 
 
print("No. of Testing Features Label:" + str(len(labels_test))) 
 
print("No. of Training Features:" + str(len(features_train))) 
 
print("No. of Training Features Label:" + str(len(labels_train))) 
 
print("No. of Predicted Features:" + str(len(pred))) 
 

 
## Calculating Classifier Performance 
 
from sklearn.metrics import classification_report 
 
y_true = labels_test 
 
y_pred = pred 
 
labels = ['0', '1'] 
 
target_names = ['class 0', 'class 1'] 
 
print(classification_report(y_true, y_pred, target_names = target_names, labels = labels)) 
 

 
# How to predict label of a new text 
 
new_text = "You won a lottery at UK lottery commission. Reply to claim it"

コードデータセットを生成するための

#!/usr/bin/python 
 

 
import os 
 
import pickle 
 
import numpy 
 
numpy.random.seed(42) 
 

 
path = os.path.dirname(os.path.abspath(__file__)) 
 

 
### The words(features) and label_data(labels), already largely processed.###These files should have been created beforehand 
 
feature_data_file = path + "./createdDataset/dataSet.pkl" 
 
label_data_file = path + "./createdDataset/dataLabel.pkl" 
 

 
feature_data = pickle.load(open(feature_data_file, "rb")) 
 
label_data = pickle.load(open(label_data_file, "rb")) 
 

 
### test_size is the percentage of events assigned to the test set(the### remainder go into training)### feature matrices changed to dense representations 
 
for compatibility with### classifier functions in versions 0.15.2 and earlier 
 
from sklearn import cross_validation 
 
features_train, features_test, labels_train, labels_test = cross_validation.train_test_split(feature_data, label_data, test_size = 0.1, random_state = 42) 
 

 
from sklearn.feature_extraction.text import TfidfVectorizer 
 
vectorizer = TfidfVectorizer(sublinear_tf = True, max_df = 0.5, stop_words = 'english') 
 
features_train = vectorizer.fit_transform(features_train) 
 
features_test = vectorizer.transform(features_test)#.toarray() 
 

 
## feature selection to reduce dimensionality 
 
from sklearn.feature_selection import SelectPercentile, f_classif 
 
selector = SelectPercentile(f_classif, percentile = 5) 
 
selector.fit(features_train, labels_train) 
 
features_train_transformed_reduced = selector.transform(features_train).toarray() 
 
features_test_transformed_reduced = selector.transform(features_test).toarray() 
 

 
features_train = features_train_transformed_reduced 
 
features_test = features_test_transformed_reduced 
 

 
def preprocess(): 
 
    return features_train, features_test, labels_train, labels_test

コードも

#!/usr/bin/python 
 

 
import os 
 
import pickle 
 
import re 
 
import sys 
 

 
# sys.path.append("../tools/") 
 

 

 
"" 
 
" 
 
    Starter code to process the texts of accuate and inaccurate category to extract 
 
    the features and get the documents ready for classification. 
 

 
    The list of all the texts from accurate category are in the accurate_files list 
 
    likewise for texts of inaccurate category are in (inaccurate_files) 
 

 
    The data is stored in lists and packed away in pickle files at the end. 
 
" 
 
"" 
 

 

 
accurate_files = open("./rawDatasetLocation/accurateFiles.txt", "r") 
 
inaccurate_files = open("./rawDatasetLocation/inaccurateFiles.txt", "r") 
 

 
label_data = [] 
 
feature_data = [] 
 

 
### temp_counter is a way to speed up the development--there are### thousands of lines of accurate and inaccurate text, so running over all of them### can take a long time### temp_counter helps you only look at the first 200 lines in the list so you### can iterate your modifications quicker 
 
temp_counter = 0 
 

 

 
for name, from_text in [("accurate", accurate_files), ("inaccurate", inaccurate_files)]: 
 
    for path in from_text: ###only look at first 200 texts when developing### once everything is working, remove this line to run over full dataset 
 
temp_counter = 1 
 
if temp_counter < 200: 
 
    path = os.path.join('..', path[: -1]) 
 
print(path) 
 
text = open(path, "r") 
 
line = text.readline() 
 
while line: ###use a 
 
function parseOutText to extract the text from the opened text# stem_text = parseOutText(text) 
 
stem_text = text.readline().strip() 
 
print(stem_text)### use str.replace() to remove any instances of the words# stem_text = stem_text.replace("germani", "")### append the text to feature_data 
 
feature_data.append(stem_text)### append a 0 to label_data 
 
if text is from Sara, and 1 
 
if text is from Chris 
 
if (name == "accurate"): 
 
    label_data.append("0") 
 
elif(name == "inaccurate"): 
 
    label_data.append("1") 
 

 
line = text.readline() 
 

 
text.close() 
 

 
print("texts processed") 
 
accurate_files.close() 
 
inaccurate_files.close() 
 

 
pickle.dump(feature_data, open("./createdDataset/dataSet.pkl", "wb")) 
 
pickle.dump(label_data, open("./createdDataset/dataLabel.pkl", "wb"))

私がしたいです私は段階的にモデルを洗練するために、より新しいデータで作成されたモデルを再トレーニングするために、クラシファイアの意味を徐々に鍛えることができるかどうかを知っていますか?

誰かがこれで私を助けることができる場合、私は本当に喜んでいるだろう。私は本当にこの時点で立ち往生しています。

+0

すでにタグ付きセットでtrain_test splitを実行してから、正確度を計算しています。新しいテストデータの場合は、新しいテストデータセットをfeatures_test変数にロードする必要があります。あなたは新しいテストデータを持つたびにあなたのNBをfit_transformするか、またはNBモデル​​を保存するか(sklearn.externals.joblib.dump/loadを使用し、新しいテストセットごとにモデルをロードして使用するあなたは漸進的に分類器を訓練することができますが、古い分類器は交換する必要があります。 – pmaniyan

答えて

1

すでにモデルを使用して、テストセット内の電子メールのラベルを予測しています。これはpred = clf.predict(features_test)の機能です。これらのラベルを表示する場合は、print predを実行してください。

しかし、おそらくあなたは、あなたが将来的に発見し、電子メールのラベルを予測することができますどのように何を知っていない現在、あなたのテストセットでありますか?そうであれば、新しい電子メールを新しいテストセットと考えることができます。以前のテストセットと同じように、あなたはデータをいくつかの主要な処理ステップを実行する必要があります。

1)あなたがする必要がある最初の事はあなたの新しい電子メールデータのための機能を生成することです。機能の生成ステップは、上記のコードには含まれていませんが、発生する必要があります。あなたがTFIDFの行列にドキュメントのコレクションを変換TFIDFベクトライザーを使用している

2)は、用語頻度と逆文書頻度に基づいています。新しい電子メールテスト機能データは、トレーニングデータに収まるベクタライザを使用して配置する必要があります。

3)新しいメールテスト機能データは、トレーニングデータに適合する同じselectorを使用して次元削減を行う必要があります。

4)最後に、新しいテストデータを予測して実行します。新しいラベルを表示する場合は、print predを使用してください。繰り返し再訓練あなたのモデルについてのあなたの最後の質問に応答する

は、はい、あなたは間違いなくこれを行うことができます。これは、入力データを使用してデータセットを展開し、そこからすべてのステップを前処理からTfidfベクトル化、次元削減、フィッティングおよび予測に再実行するスクリプトを作成するだけです。

+0

解決策Jasonに感謝します。まさに私が尋ねようとしていたことです。 – harshlal028

+0

こんにちは@ user2168281、すべての機能エンジニアリングの手順は、上記のコードの外で発生するので、言うことは不可能です。ここであなたの特徴データを引き出しています。 feature_data_file = path + "./createdDataset/dataSet.pkl" 'ここで' feature_data = pickle.load(open(feature_data_file、 "rb")) '。あなたがフィーチャー・エンジニアリングを自分でやったことがなければ、at少なくとも、ソースコードを見て追跡するどのような機能で、どのようにビルドされたので、新しいデータを最後までやり直すことができます。申し訳ありませんが、私はもっと助けません。あなたが機能の生成のためのソースコードを見つけたら、私たちに知らせてください。 – user6275647

+0

フィーチャデータは実際には電子メールのテキストそのものであり、この生の電子メールテキストデータをフィーチャに変換するのはTfidfベクタライザである可能性があります。その場合、新しい電子メールデータの機能生成は、上記のTfidfステップで行われます。しかし、この段階でインポータになった後、 'feature_data = pickle.load(open(feature_data_file、" rb "))'のような 'features_data'がどのように見えているかを見ることができないので、私は確信することはできません。 – user6275647

関連する問題