Get-Started-with-Your-Questions-EDA+Model-NN

import scipy
print(scipy.__version__)

f:id:bitop:20200103092930p:plain

リンク先

www.kaggle.com

# This Python 3 environment comes with many helpful analytics libraries installed
# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python
# For example, here's several helpful packages to load in 

#import required packages
#basics
import pandas as pd 
import numpy as np

#misc
import gc
import time
import warnings

#stats
import scipy as sp
"""
from scipy.misc import imreadでインポートするとエラーがでる
cannot import name 'imread' from 'scipy.misc'
対処法
https://qiita.com/enoughspacefor/items/c490ec7195cf66fa286f
深層学習とかでのPythonエラー「ImportError: cannot import name 'imread' from 'scipy.misc' 」への対処

scipyのバージョンが1.3にあがったのでエラーがでる

"""
from imageio import imread

from scipy import sparse
import scipy.stats as ss

#viz
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec  #https://qiita.com/simonritchie/items/da54ff0879ad8155f441 [matplotlib]プロットの複雑なレイアウトはGridSpecが便利かも、という話
import seaborn as sns
"""
ワード‐クラウド(word cloud)
文章中で出現頻度が高い単語を複数選び出し、その頻度に応じた大きさで図示する手法。 ウェブページやブログなどに
頻出する単語を自動的に並べることなどを指す。 文字の大きさだけでなく、色、字体、向きに変化をつけることで、
文章の内容をひと目で印象づけることができる。
"""
# pip install wordcloud要
from wordcloud import WordCloud ,STOPWORDS
from PIL import Image
import matplotlib_venn as venn

#nlp
import string
import re    #for regex
import nltk
from nltk.corpus import stopwords
"""
https://www.ogis-ri.co.jp/otc/hiroba/technical/similar-document-search/part4.html
はじめての自然言語処理
第1回 類似文書検索の手法と精度比較
第2回 Rasa NLU を用いた文書分類と固有表現抽出
第3回 BERT を用いた自然言語処理における転移学習
第4回 spaCy/GiNZA を用いた自然言語処理 *こんかいコレ
第5回 pke によるキーフレーズ抽出
第6回 OSS によるテキストマイニング
"""
import spacy
from nltk import pos_tag
from nltk.stem.wordnet import WordNetLemmatizer 
from nltk.tokenize import word_tokenize
# Tweet tokenizer does not split at apostophes which is what we want
from nltk.tokenize import TweetTokenizer   


#FeatureEngineering
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer, HashingVectorizer
from sklearn.decomposition import TruncatedSVD
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_X_y, check_is_fitted
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.metrics import log_loss
from sklearn.model_selection import StratifiedKFold,KFold
from sklearn.model_selection import train_test_split
import tensorflow as tf 


#settings
start_time=time.time()
color = sns.color_palette()
sns.set_style("dark")
eng_stopwords = set(stopwords.words("english"))
warnings.filterwarnings("ignore")

lem = WordNetLemmatizer()
tokenizer=TweetTokenizer()


from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator

%matplotlib inline

# Input data files are available in the "../input/" directory.
# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory

import os
for dirname, _, filenames in os.walk('/kaggle/input'):
    for filename in filenames:
        print(os.path.join(dirname, filename))

# Any results you write to the current directory are saved as output.
# pip install keras要
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Dense, Input, LSTM, Embedding, Dropout, Activation, Conv1D, GRU, BatchNormalization
from keras.layers import Bidirectional, GlobalMaxPool1D, MaxPooling1D, Add, Flatten, Masking
from keras.layers import GlobalAveragePooling1D, GlobalMaxPooling1D, concatenate, SpatialDropout1D
from keras.models import Model, load_model
from keras import initializers, regularizers, constraints, optimizers, layers, callbacks
from keras import backend as K
from keras.engine import InputSpec, Layer
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, TensorBoard, Callback, EarlyStopping, ReduceLROnPlateau
from sklearn.preprocessing import OneHotEncoder

f:id:bitop:20200103093200p:plain

Data Understanding

## load the data 
ROOT = "input/"
train = pd.read_csv(ROOT+'train.csv')
test = pd.read_csv(ROOT+'test.csv')
sub = pd.read_csv(ROOT+'sample_submission.csv')

Quick look at the train

train.head()

f:id:bitop:20200103093312p:plain

# 41 columns
print(train.columns)

f:id:bitop:20200103093355p:plain

train.shape

f:id:bitop:20200103093428p:plain

# question_title 質問のタイトル
print(train['question_title'][0])
# 訳 マクロレンズの代わりに延長チューブを使用すると、何が失われますか?
print(train['question_title'][1])
# 都市とスプロール/メトロプレックスの違いは何ですか...ダウンタウンと商業地区の違い

f:id:bitop:20200103093553p:plain

# question_user_name 質問した人の名前?
print(train['question_user_name'].unique())
print(len(train['question_user_name'].unique()))

f:id:bitop:20200103093636p:plain

#question_body 質問の中身?
print(train['question_body'][0])
"""
安価なマクロ写真で遊んだ後(読み方:レンズを逆にした、回転レンズをまっすぐなレンズに取り付けた、受動的な延長管)、私はこれをさらに進めたいと思います。 私が使用した技術の問題は、焦点が手動であり、開口制御がせいぜい問題であるということです。 これにより、私の被写体は静止した被写体に限定されました(読む:死んだ昆虫)今、春が近づいているので、生きている昆虫を撃ちたいと思います。 このためには、オートフォーカスと設定可能な絞りが大きな助けになると思います。
したがって、1つの明らかだが高価なオプションはマクロレンズ(たとえばEF 100mmマクロ)です。しかし、私はまだ別のプライムレンズにはあまり興味がありません。 代替手段は、電気延長チューブです。
最大焦点距離を除き、マクロレンズの代わりにチューブ(EF70-200 / 2.8などのファインレンズと結合)を使用すると何が失われますか?
"""
print(train['question_body'][1])
"""
Shadowrunの第5版メインブックで、p 231のスパム値がどのような場所を指しているのかを理解しようとしています。
p 15で、スプロールはプレックスであり、プレックスは「メトロポリタンの略でメトロポリタンコンプレックス」です。 Googleによると、メトロプレックスは「非常に大きな大都市圏、特に2つ以上の都市の集合体」です。 ダウンタウンの都市とスプロールダウンタウンの密度は似ている傾向がありますが、何らかの理由でスプロール(郊外を含む?)のスパムゾーンノイズ評価が高くなっています(p 231)。 同様に、繁華街は商業地区よりも密集していて騒がしい(オフィスビルや露店など)と考えています。 屋外モール。 ノイズ評価により、私はこれについて間違って考えていると思います。 それらのより良い考え方は何ですか?
"""

f:id:bitop:20200103093727p:plain

#question_user_page Stack Exchange Networkというサイトから引用されている
for i in range(10):
    print(train['question_user_page'][i])

f:id:bitop:20200103093814p:plain

# answer 答え
print(train['answer'][0])
"""
私は延長チューブを手に入れたばかりなので、ここがスキニーです。

   ...チューブを使用すると何が失われますか?

非常にかなりの量の光! レンズの端からセンサーまでの距離を長くすると、光が数回停止する場合があります。 通常は撮影を停止するという事実と組み合わせて、ISOを大幅に上げる必要があることを期待してください。
通常、マクロは非常にシャープであると考えられていますが、70-200mm 2.8は非常にシャープであると思われます。
多くのマクロに典型的な超低歪み。
自由度はまだかなり制限されるため、ボケについてはあまり心配しません。
私の50mmに加えて、完全な60mmの延長チューブは、レンズの前で数インチのDOFをもたらします。 私の70-300では、おそらくレンズの前の約2〜3フィートからレンズの前の約1フィートまでです。"""

f:id:bitop:20200103093908p:plain

# answer_user_name 質問に答えてくれた人の名前

print(train['answer_user_name'].unique())
print(len(train['answer_user_name'].unique()))

f:id:bitop:20200103093950p:plain

# answer_user_page 質問に答えてくれた人のProfileページ
for i in range(10):
    print(train['answer_user_page'][i])

f:id:bitop:20200103094050p:plain

  # url 質問と答えのページ Yahoo知恵袋のようなサイト
for i in range(10):
    print(train['url'][i])

f:id:bitop:20200103094132p:plain

print(train['category'].unique())
print(len(train['category'].unique()))
# LIFE_ARTS ?
# CULTURE 文化
# SCIENCE 科学
# STACKOVERFLOW スタックオーバーフロー
# TECHNOLOGY テクノロジ

f:id:bitop:20200103094252p:plain

print(train['host'].unique())
print(len(train['host'].unique()))

f:id:bitop:20200103094333p:plain

test.head()

f:id:bitop:20200103094421p:plain

#trainよりかなり減っている 11
test.columns

f:id:bitop:20200103094503p:plain

all_train_columns = list(train.columns)
question_answer_cols = all_train_columns[:11]
question_target_cols = all_train_columns[11:32]
answer_target_cols  = all_train_columns[32:41]

question_answer_cols

f:id:bitop:20200103094635p:plain

question_target_cols

f:id:bitop:20200103094704p:plain

answer_target_cols  

f:id:bitop:20200103094737p:plain

## Check one question and answer  
questiont = train["question_title"][0]
questionb = train["question_body"][0]
answer1 = train["answer"][0]

print(f"The First Question Topic  is : {questiont}\n\n ")
print(f"The First Question Details are :  \n\n {questionb}\n\n ")
print(f"The First answer is :\n\n {answer1}\n\n ")

f:id:bitop:20200103094845p:plain

## lets see some distributions of questions targets

# question_asker_intent_understanding
# question_body_critical
# question_conversational
# question_expect_short_answer
# question_fact_seeking
# について分布グラフを描画している

# hist=Falseはヒストグラムではなくkde=Trueガウス密度推定値を描画することを指示している
plt.figure(figsize=(20, 5))

sns.distplot(train[question_target_cols[0]], hist= False , rug= False ,kde=True, label =question_target_cols[0],axlabel =False )
sns.distplot(train[question_target_cols[1]], hist= False , rug= False,label =question_target_cols[1],axlabel =False)
sns.distplot(train[question_target_cols[2]], hist= False , rug= False,label =question_target_cols[2],axlabel =False)
sns.distplot(train[question_target_cols[3]], hist= False , rug= False,label =question_target_cols[3],axlabel =False)
sns.distplot(train[question_target_cols[4]], hist= False , rug= False,label =question_target_cols[4],axlabel =False)
plt.show()

f:id:bitop:20200103095004p:plain

## lets see some distributions of answer targets
plt.figure(figsize=(20, 5))

sns.distplot(train[answer_target_cols[0]], hist= False , rug= False ,kde=True, label =answer_target_cols[0],axlabel =False )
sns.distplot(train[answer_target_cols[1]], hist= False , rug= False,label =answer_target_cols[1],axlabel =False)
#sns.distplot(train[answer_target_cols[2]], hist= False , rug= False,label =answer_target_cols[2],axlabel =False)
#sns.distplot(train[answer_target_cols[3]], hist= False , rug= False,label =answer_target_cols[3],axlabel =False)
sns.distplot(train[answer_target_cols[4]], hist= False , rug= False,label =answer_target_cols[4],axlabel =False)
plt.show()
## Removed two columns as value was quite high and other graphs were not visible .

## Lets see the words of first question

plt.figure(figsize=(20, 5))

text = train.question_body[0]

# Create and generate a word cloud image:
wordcloud = WordCloud().generate(text)

# Display the generated image:
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

f:id:bitop:20200103095125p:plain

#アンサーの文書
### Lets see the words of first answer
plt.figure(figsize=(20, 5))

text = train.answer[0]

# Create and generate a word cloud image:
wordcloud = WordCloud().generate(text)

# Display the generated image:
plt.imshow(wordcloud, interpolation='bilinear')
plt.axis("off")
plt.show()

f:id:bitop:20200103095234p:plain

##How many words are there in all questions ? 
# 全ての質問の単語の数は
text = " ".join(question_body for question_body in train.question_body)
print(type(text))
print(test[0:10])
print ("There are {} words in the combination of all questions.".format(len(text)))

f:id:bitop:20200103095338p:plain