{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in \n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\nimport gensim\nprint(os.listdir(\"../input/embeddings\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"import gensim","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"ef67530d3d3d0aa5a60a1e0ecb23817f492d17bb"},"cell_type":"code","source":"from gensim.models import KeyedVectors\npath= '../input/embeddings/GoogleNews-vectors-negative300/GoogleNews-vectors-negative300.bin'\nword2vec=KeyedVectors.load_word2vec_format(path,binary=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f10e3f42502eaefe81e08f37c683957cf5ac398b"},"cell_type":"code","source":"embeddings=gensim.models.KeyedVectors.load_word2vec_format(path,binary=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"040d1883f9d845419ae07da360ee30494c1571cb"},"cell_type":"code","source":"len(word2vec['amazon'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"collapsed":true,"_uuid":"c2ebaecf3df522a5ea53649b512db5377186d3ac"},"cell_type":"code","source":"embeddings['amazon']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"851ef9d055aa6627b644878313f59014259955d7"},"cell_type":"code","source":"from sklearn.metrics.pairwise import cosine_similarity\ncosine_similarity([embeddings['camera'],embeddings['quality']])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a0386c4deee723bec734d3c6ad49ef65fc31372b"},"cell_type":"code","source":"embeddings.most_similar('hyundai',topn=10)  ## similar word to hyundai","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5be583a8944b81f55ccbb6a6c0bdf9a9719f320b"},"cell_type":"code","source":"embeddings.doesnt_match(['rahul','sonia','gandhi','sachin'])  ## getting the odd man out","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b11fe34a2044f49e952605a3eae791520d8306c3"},"cell_type":"code","source":"embeddings.most_similar(positive=['king','women'],negative=['man'],topn=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f728720305a987aa6746403e46d5709ee6531c97"},"cell_type":"markdown","source":"Using IMDb dataset"},{"metadata":{"trusted":true,"_uuid":"10ae91820b3380ec773e62f423956ca8b5f12efd"},"cell_type":"code","source":"url=\"https://raw.githubusercontent.com/skathirmani/datasets/master/imdb_sentiment.csv\"\nimdb=pd.read_csv(url)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4f6ed240e94b88c742b42e7d4e665b926ac56883"},"cell_type":"code","source":"### document term matrix is created usings weight assign to words\n## as normal document term matrix has very high dimension\n# reducing the dimension by assigning weight","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"00501a0243d3ca1e3ac45854869c038a859305a8"},"cell_type":"code","source":"imdb.head(2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"df08fd5f68d668cd557632eda27355e9040934ab"},"cell_type":"code","source":"### it wil fail when word in docement does not match word in google","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"bc8c9380dd2119adad4e5a595aec74348ecac7c7"},"cell_type":"code","source":"import nltk\ndocs_vectors=pd.DataFrame()\nstopwords=nltk.corpus.stopwords.words('english')  ### do not do stemming\nfor doc in imdb['review'].str.lower().str.replace('[^a-z ]',' '):\n    words=nltk.word_tokenize(doc)\n    words_clean=[word for word in words if word not in stopwords]\n    temp=pd.DataFrame()\n    for word in words_clean:     ### looping through allthe words in a document\n        try:\n            word_vec=pd.Series(embeddings[word])\n            temp=temp.append(word_vec,ignore_index=True)\n        except:\n            pass\n    temp_avg=temp.mean()        ### calculating the mean(column sum)\n    docs_vectors=docs_vectors.append(temp_avg,ignore_index=True)\ndocs_vectors.shape   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"837a4628118f36287d81b0c9f846bbb158b55d0f"},"cell_type":"code","source":"docs_vectors ## vector representation of each word","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"01e880155a7c636cd77d625a1876589192cfd288"},"cell_type":"code","source":"pd.isnull(docs_vectors).sum().sum()  ##nearly 2 rows is completely missing","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6857967222f5606bea3291218ec933402351bf35"},"cell_type":"code","source":"docs_vectors['sentiment']=imdb['sentiment']\ndocs_vectors=docs_vectors.dropna()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"52671895d444ad3f07dc3cca65666c4d73cb817d"},"cell_type":"code","source":"docs_vectors.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"49a076b399ae78db9f1b0ce2a0a0cb061eb81912"},"cell_type":"code","source":"### cant use multinomial naive baise as it contain negative values","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e72ba5ae62db1565f04204e6b9ae28bcca241de6"},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score,classification_report\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier,GradientBoostingClassifier","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e1c0eebccc912e937d152d308969f7323fdb7102"},"cell_type":"code","source":"train,test=train_test_split(docs_vectors,test_size=0.2,random_state=100)\ntrain_x=train.drop('sentiment',axis=1)\ntrain_y=train['sentiment']\ntest_x=test.drop('sentiment',axis=1)\ntest_y=test['sentiment']\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7b9e574a8af7ef054b76df15e4af548e573fc916"},"cell_type":"code","source":"ab_model = AdaBoostClassifier(n_estimators=300,random_state=100)\nab_model.fit(train_x,train_y)\nab_pred =ab_model.predict(test_x)\naccuracy_score(test_y,ab_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"425e039e4c7996d7054422085b74090ddc4875ee"},"cell_type":"code","source":"ab_pred[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"2274cb570414f0f997696e3392dc3105fed878d0"},"cell_type":"code","source":"gb_model = GradientBoostingClassifier(n_estimators=300,random_state=100)\ngb_model.fit(train_x,train_y)\ngb_pred =gb_model.predict(test_x)\naccuracy_score(test_y,gb_pred)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"620d2de93167bc81ebb34823db71709802740023"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"19bdce389a505b693ea577d0aeda493eaffc1816"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8a7d49f961b2ff5aab109a8842dc70142567252f"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cf1551c7b5c821220326ff72a6069172ef8fe05d"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"31fc6f16e8bea285d316ce5753e3c80ffb927aef"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"e346692361a98696b7dac5854cb647fccd263cb5"},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}