{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import pandas as pd\nimport re","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"# I. Data Overview","metadata":{}},{"cell_type":"markdown","source":"> **1. Load dữ liệu**","metadata":{}},{"cell_type":"code","source":"train_df = pd.read_csv(\"../input/quora-insincere-questions-classification/train.csv\")\ntest_df = pd.read_csv(\"../input/quora-insincere-questions-classification/test.csv\")\ntrain_df\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**=> Nhận xét:** \n\n* Về yêu cầu bài toán ta thấy đây là bài toán phân lớp nhị phân, mục đích là phải detect được câu hỏi nào là toxic\n* Nhìn vào question_text thì ta có thể thấy rằng đây là dữ liệu tiếng anh, mỗi mẫu là các câu hỏi, nhìn chung các câu hỏi này hỏi về vấn đề chính trị, giáo dục, giới tính,... Là chủ đề về xã hội. \n* cần phải được tiền xử lý qua các bước như đưa về dạng gốc, tokenize, loại bỏ stop words, loại bỏ dấu,...","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\nlabels = [ 'untoxic question', 'toxic question']\nx = train_df['target'].value_counts().to_list()\ny = labels\nplt.xticks(fontsize =12)\nplt.yticks(fontsize =12)\nplt.xlabel('Polarity',fontsize =13)\nplt.ylabel('Number of question',fontsize = 13)\n# plt.xticks(rotation)\ncolor_list = [ '#FF6565', '#2C99FE']\nplt.bar(y,x,color = color_list,width=0.3, align='center',)\nplt.title('Data Distribution')\nplt.figure(figsize=(5,10))\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**=> Nhận xét:** \n* nhìn vào biểu đồ trên ta thấy dữ liệu gặp phải vấn đề mất cân bằng. Cụ thể là nhãn có score là 1 (chính là nhãn toxic) ít hơn rất nhiều so với nhãn có score là 0 ( nhãn bình thường)","metadata":{}},{"cell_type":"markdown","source":"# II. Làm sạch dữ liệu:\n> **1. Loại bỏ punctuation, viết thường các chữ**\n","metadata":{}},{"cell_type":"code","source":"puncts = [\n    '½', '¿', 'ï', '¸', '-', ',', '/', '\"', '¨', '²', 'è', '×', '❤', '，', '↓', '▾', '↑',\n    'Ã', '±', ']', '·', '_', '<', '?', '⋅', '™', '~', '→', '′', '>', '≤', '€', '¥', '¼',\n    '¶', '@', '√', '®', '\\\\', '…', '、', '¹', '$', '•', '!', '¯', '&', '†', ')', '・', '^',\n    '—', '+', '#', '（', '³', '£', '″', '−', '[', '¬', '¦', '）', '–', '”', '¢', '%', '©',\n    '»', '}', '¾', '§', '=', '{', '‘', '∞', 'Ø', '°', '|', '：', '▒', 'â', 'à', ':', '(',\n    ';', '`', '│', 'é', '*', '’', '.', '\\'', '“',\n]\n\ndef remove_punctuation(text):\n    for punct in puncts:\n        if punct in text:\n            text = text.lower()\n            text = text.replace(punct, '')\n            text = text.strip()\n    return text\n\ntrain_df['question_text'] = train_df['question_text'].apply(remove_punctuation)\ntest_df['question_text'] = test_df['question_text'].apply(remove_punctuation)\ntrain_df.question_text[0]","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> **2. Loại bỏ các số**","metadata":{}},{"cell_type":"code","source":"def remove_numbers(text):\n    text_removed_number = ''.join([i for i in text if not i.isdigit()])\n    return text_removed_number\ntrain_df['question_text'] = train_df['question_text'].apply(remove_numbers)\ntest_df['question_text'] = test_df['question_text'].apply(remove_numbers)\ntrain_df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"> **2. Tokenize text**","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"\ndef tokenize(text):\n    tokens =re.split('\\W+',text)\n    return tokens\n\ntrain_df['question_text']= train_df['question_text'].apply(tokenize)\ntest_df['question_text']= test_df['question_text'].apply(tokenize)\ntrain_df.head\n    ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> **3. Remove stopword:**\n","metadata":{}},{"cell_type":"code","source":"import nltk\nfrom nltk.corpus import stopwords\n\nstopword =nltk.corpus.stopwords.words('english')\n\ndef remove_stopwords(tokenized_list):\n    text = [word for word in tokenized_list if word not in stopword]\n    return text\n\ntrain_df['question_text'] = train_df['question_text'].apply(remove_stopwords)\ntest_df['question_text'] = test_df['question_text'].apply(remove_stopwords)\ntrain_df.head","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"> **4. Lemmatizing**","metadata":{}},{"cell_type":"code","source":"wn = nltk.WordNetLemmatizer()\n\ndef lemmatizing(tokenized_text):\n    text = [wn.lemmatize(word) for word in tokenized_text]\n    return text\n\ntrain_df['question_text'] = train_df['question_text'].apply(lambda x: lemmatizing(x))\ntest_df['question_text'] = test_df['question_text'].apply(lambda x: lemmatizing(x))\n\ntrain_df.head()\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# III. Biểu diễn dữ liệu\n","metadata":{}},{"cell_type":"markdown","source":"> **1. chọn đặc trưng dùng SelectKBest với score_func là chi2**","metadata":{}},{"cell_type":"code","source":"def feature_select(corpus, labels, k=1000000):\n    \"\"\"\n    select top k features through chi-square test\n    \"\"\"\n    bin_cv = CountVectorizer(analyzer=\"word\", tokenizer=None, preprocessor=None, stop_words=None, binary=True)\n    le = LabelEncoder()\n    X = bin_cv.fit_transform(corpus, np.nan)\n    y = le.fit_transform(labels).reshape(-1, 1)\n\n    skb = SelectKBest(chi2, k='all')\n    skb.fit(X, y)\n\n    feature_ids = skb.get_support(indices=True)\n    feature_names = bin_cv.get_feature_names()\n    result = {}\n    vocab = []\n\n    for new_fid, old_fid in enumerate(feature_ids):\n        feature_name = feature_names[old_fid]\n        vocab.append(feature_name)\n\n    result['text'] = vocab\n    result['_score'] = list(skb.scores_)\n    result['_pvalue'] = list(skb.pvalues_)\n\n    return result","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"corpus = []\nfor question in train_df.question_text:\n    corpus.append(' '.join(question))\ncorpus\nscores = []\nfor score in train_df.target:\n    scores.append(score)\nfile_out = feature_select(corpus, scores)\ndf = pd.DataFrame(file_out)\ndf = df.sort_values('_score', ascending=False)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"* **Chuẩn hóa điểm score của chi2 về trong khoảng 0 đến 1 dùng Min_max scaling**","metadata":{}},{"cell_type":"code","source":"from sklearn.preprocessing import MinMaxScaler\ndef scaling(data):\n    scaler = MinMaxScaler()\n    scaler.fit(data)\n    scores = scaler.transform(data)\n    return scores\nscores = np.array(df._score)\nscores = scores.reshape((len(scores),1))\ndf._score = scaling(scores).reshape((len(scores)))\ndf.to_csv('./chi2_vocabulary.csv', ',', encoding='utf-8')\ndf\n\n\n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"> **2. Biểu diễn dữ liệu**","metadata":{}},{"cell_type":"markdown","source":"Sau khi dùng chi2 để đánh trọng số các từ, tiến hành lọc vocab theo ngưỡng điểm _score","metadata":{}},{"cell_type":"code","source":"#load vocabulary\nvocab_df = pd.read_csv(\"../input/chisquare/chi2_vocab.csv\")\nvocab_df\nX_train = []\nfor text in train_df.question_text:\n    encoding = [v['_score'] if v['text'] else 0 in text for v in vocab_df]\n    X_train.append(encoding)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# IV. Huấn Luyện mô hình","metadata":{}},{"cell_type":"markdown","source":"> **1. Chọn model**\n","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"from sklearn.linear_model import LogisticRegression\nmodel = LogisticRegression()\nmodel.fit()","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}