LoginSignup
0
2

More than 5 years have passed since last update.

Kaggleのデータからbag of wordsを作ってみた(3/3)

Last updated at Posted at 2017-07-30

初めに

この記事はKaggleのデータ「Bag of Words Meets Bags of Popcorn」のデータでbag of wordsを作り、Random Forestで予測するまでを説明する初心者向けの記事です。
英語記事でいいものを見つけたので、英語が苦手な方向けに和訳+初心者向けに補足したものになっております。
また、投稿自体が初めてのなのでアドバイスをいただければ幸いです。
Kaggleのデータからbag of wordsを作ってみた(1/3)
Kaggleのデータからbag of wordsを作ってみた(2/3)

環境

  • Python 3.6.0 :: Anaconda custom (x86_64)
  • Mac OS X 10.12.5

この章で行うこと

  • 前回作成したレビューデータからのbag of wordsを用いてのRandom Forestの学習と予測
#Random Forest
print("Training the random forest...")
from sklearn.ensemble import RandomForestClassifier
# 初期化
forest = RandomForestClassifier(n_estimators = 100) 
#Random Forestの学習
forest = forest.fit( train_data_features, train["sentiment"] )

次にテストデータのクリーニングを行います。

#テストデータの読み込み
test = pd.read_csv("testData.tsv", header=0, delimiter="\t", \
                   quoting=3 

# ここで25,000 rows and 2 columnsのデータだと確認
print (test.shape)

#テストデータのクリーニング
for i in range(0,num_reviews):
    if( (i+1) % 1000 == 0 ):
        print ("Review %d of %d\n" % (i+1, num_reviews))
    clean_review = review_to_words( test["review"][i] )
    clean_test_reviews.append( clean_review )

#ここでテストデータを単語ベクトルの形に変換する
test_data_features = vectorizer.transform(clean_test_reviews)
test_data_features = test_data_features.toarray()

#学習した Random Forestを用いて予測
result = forest.predict(test_data_features)

#予測結果をcsvファイルに変換(kaggleでは予測結果をcsvで提出することが一般的であるため)
output = pd.DataFrame( data={"id":test["id"], "sentiment":result} )
output.to_csv( "Bag_of_Words_model.csv", index=False, quoting=3 )

参考文献

Part 1: For Beginners - Bag of Words

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2