{"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":"# 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\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 read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-05-30T09:35:22.276102Z","iopub.execute_input":"2023-05-30T09:35:22.276500Z","iopub.status.idle":"2023-05-30T09:35:22.296347Z","shell.execute_reply.started":"2023-05-30T09:35:22.276470Z","shell.execute_reply":"2023-05-30T09:35:22.295197Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Importing libraries","metadata":{}},{"cell_type":"code","source":"# Basic imports\n \nimport torch \nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt ","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:22.298722Z","iopub.execute_input":"2023-05-30T09:35:22.299644Z","iopub.status.idle":"2023-05-30T09:35:22.304969Z","shell.execute_reply.started":"2023-05-30T09:35:22.299602Z","shell.execute_reply":"2023-05-30T09:35:22.303911Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Load dataset","metadata":{}},{"cell_type":"code","source":"# import the data \ndata = pd.read_csv(\"../input/predict-closed-questions-on-stack-overflow/train-sample.csv\")\ndata.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:22.306363Z","iopub.execute_input":"2023-05-30T09:35:22.306693Z","iopub.status.idle":"2023-05-30T09:35:25.162074Z","shell.execute_reply.started":"2023-05-30T09:35:22.306665Z","shell.execute_reply":"2023-05-30T09:35:25.161218Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.info()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:25.164319Z","iopub.execute_input":"2023-05-30T09:35:25.165054Z","iopub.status.idle":"2023-05-30T09:35:25.654316Z","shell.execute_reply.started":"2023-05-30T09:35:25.165010Z","shell.execute_reply":"2023-05-30T09:35:25.652995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Exploratory Data Analysis","metadata":{}},{"cell_type":"markdown","source":"### PostID\n##### This feature is the id of the query posted by the user. This feauture does not have any importance in making the prediction but it will be used later for submission we will save it.","metadata":{}},{"cell_type":"code","source":"data_id=data.PostId","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:25.655728Z","iopub.execute_input":"2023-05-30T09:35:25.656176Z","iopub.status.idle":"2023-05-30T09:35:25.660967Z","shell.execute_reply.started":"2023-05-30T09:35:25.656135Z","shell.execute_reply":"2023-05-30T09:35:25.659915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### PostCreationDate\n##### The post creation date is the date and time on which the query was posted by the user let us see if we could make something out of this.\n\n##### As we have observed that it doesn't matter on the time the question is posted on its label thus we can just remove this column both from our train and test.","metadata":{}},{"cell_type":"code","source":"data.drop(['PostCreationDate'],axis=1,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:25.662384Z","iopub.execute_input":"2023-05-30T09:35:25.663428Z","iopub.status.idle":"2023-05-30T09:35:25.698237Z","shell.execute_reply.started":"2023-05-30T09:35:25.663386Z","shell.execute_reply":"2023-05-30T09:35:25.697087Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### OwnerUserId\n##### This is the user id who posted the query. Let us check it","metadata":{}},{"cell_type":"code","source":"data['PostCount']=[1]*len(data['PostId'])","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:25.699610Z","iopub.execute_input":"2023-05-30T09:35:25.700014Z","iopub.status.idle":"2023-05-30T09:35:25.777709Z","shell.execute_reply.started":"2023-05-30T09:35:25.699979Z","shell.execute_reply":"2023-05-30T09:35:25.776536Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.pivot_table(data,index='OwnerUserId',columns='OpenStatus',values='PostCount',aggfunc='sum')","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:25.779506Z","iopub.execute_input":"2023-05-30T09:35:25.780297Z","iopub.status.idle":"2023-05-30T09:35:25.945611Z","shell.execute_reply.started":"2023-05-30T09:35:25.780263Z","shell.execute_reply":"2023-05-30T09:35:25.944321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.loc[data['OpenStatus']=='open','OwnerUserId'].value_counts()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:25.946902Z","iopub.execute_input":"2023-05-30T09:35:25.947284Z","iopub.status.idle":"2023-05-30T09:35:25.991096Z","shell.execute_reply.started":"2023-05-30T09:35:25.947255Z","shell.execute_reply":"2023-05-30T09:35:25.989821Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We see that it does not matter on the OwnerUserId whether his question is going to be open or not as there are many user whose only one question remain open So, we would be dropping this column","metadata":{}},{"cell_type":"code","source":"data.drop(['OwnerUserId'],axis=1,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:25.996390Z","iopub.execute_input":"2023-05-30T09:35:25.997074Z","iopub.status.idle":"2023-05-30T09:35:26.027796Z","shell.execute_reply.started":"2023-05-30T09:35:25.997001Z","shell.execute_reply":"2023-05-30T09:35:26.026963Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Reputation at Post Created\n##### This can be a important factor. Let's take a look at it","metadata":{}},{"cell_type":"code","source":"data['ReputationAtPostCreation'].min()\n","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.029162Z","iopub.execute_input":"2023-05-30T09:35:26.029756Z","iopub.status.idle":"2023-05-30T09:35:26.036585Z","shell.execute_reply.started":"2023-05-30T09:35:26.029723Z","shell.execute_reply":"2023-05-30T09:35:26.035375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data['ReputationAtPostCreation'].max()\n","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.037994Z","iopub.execute_input":"2023-05-30T09:35:26.038374Z","iopub.status.idle":"2023-05-30T09:35:26.049421Z","shell.execute_reply.started":"2023-05-30T09:35:26.038345Z","shell.execute_reply":"2023-05-30T09:35:26.048467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Since the data range is such high let us scale it using MinMaxScaler\nminimum=data['ReputationAtPostCreation'].min()\nmaximum=data['ReputationAtPostCreation'].max()\ndata['ReputationAtPostCreation']=(data['ReputationAtPostCreation']-minimum)/(maximum-minimum)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.050895Z","iopub.execute_input":"2023-05-30T09:35:26.051226Z","iopub.status.idle":"2023-05-30T09:35:26.062821Z","shell.execute_reply.started":"2023-05-30T09:35:26.051200Z","shell.execute_reply":"2023-05-30T09:35:26.061674Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### OwnerUndeletedAnswerCountAtPostTime","metadata":{}},{"cell_type":"code","source":"data.OwnerUndeletedAnswerCountAtPostTime.value_counts()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.064089Z","iopub.execute_input":"2023-05-30T09:35:26.064409Z","iopub.status.idle":"2023-05-30T09:35:26.081095Z","shell.execute_reply.started":"2023-05-30T09:35:26.064383Z","shell.execute_reply":"2023-05-30T09:35:26.080102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"This feature doesnot seem to be doing anything, we will be dropping it for now.\n","metadata":{}},{"cell_type":"code","source":"data.drop(['OwnerUndeletedAnswerCountAtPostTime'],axis=1,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.082157Z","iopub.execute_input":"2023-05-30T09:35:26.083194Z","iopub.status.idle":"2023-05-30T09:35:26.116584Z","shell.execute_reply.started":"2023-05-30T09:35:26.083162Z","shell.execute_reply":"2023-05-30T09:35:26.115631Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### PostClosedDate¶\n##### Dropping this column as post closed date does not seem to be doing anything, so we would be dropping it","metadata":{}},{"cell_type":"code","source":"data.drop(['PostClosedDate'],axis=1,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.118008Z","iopub.execute_input":"2023-05-30T09:35:26.118377Z","iopub.status.idle":"2023-05-30T09:35:26.148658Z","shell.execute_reply.started":"2023-05-30T09:35:26.118348Z","shell.execute_reply":"2023-05-30T09:35:26.147648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### tag1","metadata":{}},{"cell_type":"code","source":"data['Tag1'].isnull().sum()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.150123Z","iopub.execute_input":"2023-05-30T09:35:26.150642Z","iopub.status.idle":"2023-05-30T09:35:26.174821Z","shell.execute_reply.started":"2023-05-30T09:35:26.150602Z","shell.execute_reply":"2023-05-30T09:35:26.173675Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"We can combine all the tags column into one this would help us in comparing the words which are used as tags and the words used in Title and Body.","metadata":{}},{"cell_type":"code","source":"data['Tag1']=data['Tag1'].replace(np.nan,' ')\ndata['Tag2']=data['Tag2'].replace(np.nan,' ')\ndata['Tag3']=data['Tag3'].replace(np.nan,' ')\ndata['Tag4']=data['Tag4'].replace(np.nan,' ')\ndata['Tag5']=data['Tag5'].replace(np.nan,' ')","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.176281Z","iopub.execute_input":"2023-05-30T09:35:26.177088Z","iopub.status.idle":"2023-05-30T09:35:26.335659Z","shell.execute_reply.started":"2023-05-30T09:35:26.177027Z","shell.execute_reply":"2023-05-30T09:35:26.334646Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#combine all tags to make a new column\ndata['Tags']=data['Tag1']+' '+data['Tag2']+' '+data['Tag3']+' '+data['Tag4']+' '+data['Tag5']","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.337412Z","iopub.execute_input":"2023-05-30T09:35:26.337854Z","iopub.status.idle":"2023-05-30T09:35:26.515505Z","shell.execute_reply.started":"2023-05-30T09:35:26.337814Z","shell.execute_reply":"2023-05-30T09:35:26.514565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data['Tags']","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.517354Z","iopub.execute_input":"2023-05-30T09:35:26.517802Z","iopub.status.idle":"2023-05-30T09:35:26.527393Z","shell.execute_reply.started":"2023-05-30T09:35:26.517759Z","shell.execute_reply":"2023-05-30T09:35:26.526289Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#change to lowercase\ndata['Tags']=data['Tags'].str.lower()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.528802Z","iopub.execute_input":"2023-05-30T09:35:26.529174Z","iopub.status.idle":"2023-05-30T09:35:26.596544Z","shell.execute_reply.started":"2023-05-30T09:35:26.529142Z","shell.execute_reply":"2023-05-30T09:35:26.595411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#remove white spaces in left and right places\ndata['Tags']=data['Tags'].apply(lambda x:x.lstrip())\ndata['Tags']=data['Tags'].apply(lambda x:x.rstrip())","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.597957Z","iopub.execute_input":"2023-05-30T09:35:26.598359Z","iopub.status.idle":"2023-05-30T09:35:26.707980Z","shell.execute_reply.started":"2023-05-30T09:35:26.598328Z","shell.execute_reply":"2023-05-30T09:35:26.706785Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.709673Z","iopub.execute_input":"2023-05-30T09:35:26.710052Z","iopub.status.idle":"2023-05-30T09:35:26.728896Z","shell.execute_reply.started":"2023-05-30T09:35:26.710004Z","shell.execute_reply":"2023-05-30T09:35:26.727565Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Dropping excess columns \ndata.drop(['PostId','OwnerCreationDate','Tag1','Tag2','Tag3','Tag4','Tag5','PostCount'],axis=1,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.730285Z","iopub.execute_input":"2023-05-30T09:35:26.730713Z","iopub.status.idle":"2023-05-30T09:35:26.750484Z","shell.execute_reply.started":"2023-05-30T09:35:26.730667Z","shell.execute_reply":"2023-05-30T09:35:26.749244Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.752370Z","iopub.execute_input":"2023-05-30T09:35:26.752804Z","iopub.status.idle":"2023-05-30T09:35:26.767122Z","shell.execute_reply.started":"2023-05-30T09:35:26.752761Z","shell.execute_reply":"2023-05-30T09:35:26.765993Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.drop(['ReputationAtPostCreation'],axis=1,inplace=True)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.769160Z","iopub.execute_input":"2023-05-30T09:35:26.769597Z","iopub.status.idle":"2023-05-30T09:35:26.787296Z","shell.execute_reply.started":"2023-05-30T09:35:26.769555Z","shell.execute_reply":"2023-05-30T09:35:26.786202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Feature selection","metadata":{}},{"cell_type":"code","source":"# Let's take 'TITLE' & 'BODYMARKDOWN' & OpenStatus Columns \ndata_train = data[['Title', 'BodyMarkdown','Tags', 'OpenStatus']]\ndata_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.788629Z","iopub.execute_input":"2023-05-30T09:35:26.789622Z","iopub.status.idle":"2023-05-30T09:35:26.835747Z","shell.execute_reply.started":"2023-05-30T09:35:26.789572Z","shell.execute_reply":"2023-05-30T09:35:26.834471Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_train.shape","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.843320Z","iopub.execute_input":"2023-05-30T09:35:26.843701Z","iopub.status.idle":"2023-05-30T09:35:26.850849Z","shell.execute_reply.started":"2023-05-30T09:35:26.843668Z","shell.execute_reply":"2023-05-30T09:35:26.849528Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Sample 80k randomly! \ndata_train = data_train.sample(80000, random_state = 234)\ndata_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.852509Z","iopub.execute_input":"2023-05-30T09:35:26.852921Z","iopub.status.idle":"2023-05-30T09:35:26.893193Z","shell.execute_reply.started":"2023-05-30T09:35:26.852888Z","shell.execute_reply":"2023-05-30T09:35:26.892051Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Fill NaN values with empty strings\ndata_train = data_train.fillna('')\n\n# Display the updated dataset\ndata_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:26.894789Z","iopub.execute_input":"2023-05-30T09:35:26.895148Z","iopub.status.idle":"2023-05-30T09:35:27.032068Z","shell.execute_reply.started":"2023-05-30T09:35:26.895119Z","shell.execute_reply":"2023-05-30T09:35:27.030836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_train.isna().sum()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:27.033298Z","iopub.execute_input":"2023-05-30T09:35:27.033614Z","iopub.status.idle":"2023-05-30T09:35:27.164156Z","shell.execute_reply.started":"2023-05-30T09:35:27.033587Z","shell.execute_reply":"2023-05-30T09:35:27.163060Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Preprocessing","metadata":{}},{"cell_type":"code","source":"import nltk\nimport re\nimport string\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\n\n# Download required resources (only need to do this once)\nnltk.download('stopwords')\nnltk.download('punkt')\nnltk.download('wordnet')\n\n# Define the preprocessing function\ndef preprocess_text(text):\n    # Convert to lowercase\n    text = text.lower()\n    \n    # Remove HTML tags\n    text = remove_html_tags(text)\n    \n    #Remove URL tags\n    text = remove_urls(text)\n    \n    # Remove special characters and numbers\n    text = re.sub(r'[^a-zA-Z]', ' ', text)\n    \n    # Tokenize the text into individual words\n    tokens = word_tokenize(text)\n    \n    # Remove stopwords\n    stop_words = set(stopwords.words('english'))\n    tokens = [word for word in tokens if word not in stop_words]\n    \n    # Lemmatize the words\n    #lemmatizer = WordNetLemmatizer()\n    #tokens = [lemmatizer.lemmatize(word) for word in tokens]\n    \n    # Join the tokens back into a single string\n    preprocessed_text = ' '.join(tokens)\n    \n    return preprocessed_text\n\n# Function to remove HTML tags\ndef remove_html_tags(text):\n    pattern = re.compile('<.*?>')\n    return pattern.sub(r'', text)\n\n# Function to remove URL links\ndef remove_urls(text):\n    pattern = re.compile(r'http\\S+|www\\S+')\n    return pattern.sub(r'', text)\n\n# Apply preprocessing to the 'Title' and 'BodyMarkdown' columns\ndata_train['Title'] = data_train['Title'].apply(preprocess_text)\ndata_train['BodyMarkdown'] = data_train['BodyMarkdown'].apply(preprocess_text)\ndata_train['Tags'] = data_train['Tags'].apply(preprocess_text)\n\n# Display the preprocessed dataset\nprint(data_train.head())","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:35:27.165580Z","iopub.execute_input":"2023-05-30T09:35:27.165921Z","iopub.status.idle":"2023-05-30T09:38:22.681910Z","shell.execute_reply.started":"2023-05-30T09:35:27.165891Z","shell.execute_reply":"2023-05-30T09:38:22.680867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Lets see the the data!\ndata_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:38:22.683118Z","iopub.execute_input":"2023-05-30T09:38:22.683493Z","iopub.status.idle":"2023-05-30T09:38:22.695439Z","shell.execute_reply.started":"2023-05-30T09:38:22.683467Z","shell.execute_reply":"2023-05-30T09:38:22.694613Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_train.OpenStatus.unique()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:38:22.696774Z","iopub.execute_input":"2023-05-30T09:38:22.697475Z","iopub.status.idle":"2023-05-30T09:38:22.719191Z","shell.execute_reply.started":"2023-05-30T09:38:22.697445Z","shell.execute_reply":"2023-05-30T09:38:22.718091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\n\n# Create an instance of LabelEncoder\nencoder = LabelEncoder()\n\n# Fit the encoder on the 'OpenStatus' column\nencoder.fit(data_train['OpenStatus'])\n\n# Encode the 'OpenStatus' column\ndata_train['OpenStatus'] = encoder.transform(data_train['OpenStatus'])","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:38:22.720609Z","iopub.execute_input":"2023-05-30T09:38:22.721340Z","iopub.status.idle":"2023-05-30T09:38:22.756749Z","shell.execute_reply.started":"2023-05-30T09:38:22.721301Z","shell.execute_reply":"2023-05-30T09:38:22.755446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"list(encoder.classes_)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:38:22.758320Z","iopub.execute_input":"2023-05-30T09:38:22.758739Z","iopub.status.idle":"2023-05-30T09:38:22.770103Z","shell.execute_reply.started":"2023-05-30T09:38:22.758705Z","shell.execute_reply":"2023-05-30T09:38:22.768915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#change the unique elements in openstatus column to \n#data_train['OpenStatus']= data_train['OpenStatus'].map({'open': 0, 'not a real question': 1, 'off topic': 2, 'not constructive': 3, 'too localized': 4}) \ndata_train.head()","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:38:22.771653Z","iopub.execute_input":"2023-05-30T09:38:22.772677Z","iopub.status.idle":"2023-05-30T09:38:22.792928Z","shell.execute_reply.started":"2023-05-30T09:38:22.772643Z","shell.execute_reply":"2023-05-30T09:38:22.792119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## split the data into train and test","metadata":{}},{"cell_type":"code","source":"# firstly seperate x and y: \nx = data_train['Title'] + ' '+ data_train['BodyMarkdown']+' '+data_train['Tags']\ny = data_train['OpenStatus']\n\n# xtrain, ytrian \nfrom sklearn.model_selection import train_test_split \nxtrain, xtest, ytrain, ytest = train_test_split(x, y, test_size = 0.3, random_state = 203)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:38:22.794363Z","iopub.execute_input":"2023-05-30T09:38:22.794869Z","iopub.status.idle":"2023-05-30T09:38:22.980732Z","shell.execute_reply.started":"2023-05-30T09:38:22.794840Z","shell.execute_reply":"2023-05-30T09:38:22.979517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Let's covvert words to numbers using TF-IDF \nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\nvectorizer = TfidfVectorizer(max_features = 10000)  # it contains only 10k features (fixed!)\n\nxtrain_tfidf = vectorizer.fit_transform(xtrain).toarray()  # converting words to numbers for train data \nxtest_tfidf = vectorizer.transform(xtest).toarray()        # converting words to numbers for test data ","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:38:22.982398Z","iopub.execute_input":"2023-05-30T09:38:22.982839Z","iopub.status.idle":"2023-05-30T09:38:38.167579Z","shell.execute_reply.started":"2023-05-30T09:38:22.982797Z","shell.execute_reply":"2023-05-30T09:38:38.166473Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtest_tfidf.shape","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:38:38.168998Z","iopub.execute_input":"2023-05-30T09:38:38.169383Z","iopub.status.idle":"2023-05-30T09:38:38.176915Z","shell.execute_reply.started":"2023-05-30T09:38:38.169349Z","shell.execute_reply":"2023-05-30T09:38:38.175702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"xtrain_tfidf.shape","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:38:38.179104Z","iopub.execute_input":"2023-05-30T09:38:38.179786Z","iopub.status.idle":"2023-05-30T09:38:38.192265Z","shell.execute_reply.started":"2023-05-30T09:38:38.179745Z","shell.execute_reply":"2023-05-30T09:38:38.191133Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### modeling","metadata":{}},{"cell_type":"code","source":"from kerastuner.tuners import RandomSearch\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout\n\ndef build_model(hp):\n    model = Sequential()\n    model.add(Dense(units=hp.Int('units_1', min_value=32, max_value=256, step=32),\n                    activation='relu',\n                    input_shape=(xtrain_tfidf.shape[1],)))\n    model.add(Dropout(rate=hp.Float('dropout_1', min_value=0.2, max_value=0.5, step=0.1)))\n    model.add(Dense(units=hp.Int('units_2', min_value=32, max_value=128, step=32),\n                    activation='relu'))\n    model.add(Dropout(rate=hp.Float('dropout_2', min_value=0.2, max_value=0.5, step=0.1)))\n    model.add(Dense(5, activation='softmax'))\n\n    model.compile(optimizer=Adam(hp.Choice('learning_rate', values=[1e-2, 1e-3, 1e-4])),\n                  loss='sparse_categorical_crossentropy',\n                  metrics=['accuracy'])\n\n    return model\n\n# Define the tuner\ntuner = RandomSearch(\n    build_model,\n    objective='val_accuracy',\n    max_trials=10,\n    directory='tuner_directory',\n    project_name='hyperparameter_tuning')\n\n# Perform hyperparameter tuning\ntuner.search(xtrain_tfidf, ytrain,\n             epochs=10,\n             validation_split=0.2,\n             callbacks=[EarlyStopping(patience=3)])\n\n# Get the best model\nbest_model = tuner.get_best_models(num_models=1)[0]\n\n# Evaluate the best model on the test set\nloss, accuracy = best_model.evaluate(xtest_tfidf, ytest)\nprint('Test Accuracy:', accuracy)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:38:38.193622Z","iopub.execute_input":"2023-05-30T09:38:38.194070Z","iopub.status.idle":"2023-05-30T09:59:36.304356Z","shell.execute_reply.started":"2023-05-30T09:38:38.194017Z","shell.execute_reply":"2023-05-30T09:59:36.303125Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### scoring","metadata":{}},{"cell_type":"code","source":"y_pred=best_model.predict(xtest_tfidf)","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:59:36.306137Z","iopub.execute_input":"2023-05-30T09:59:36.307215Z","iopub.status.idle":"2023-05-30T09:59:41.679652Z","shell.execute_reply.started":"2023-05-30T09:59:36.307179Z","shell.execute_reply":"2023-05-30T09:59:41.678454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:59:41.681263Z","iopub.execute_input":"2023-05-30T09:59:41.681696Z","iopub.status.idle":"2023-05-30T09:59:41.690860Z","shell.execute_reply.started":"2023-05-30T09:59:41.681655Z","shell.execute_reply":"2023-05-30T09:59:41.689364Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred_final=np.argmax(y_pred,axis=1)\ny_pred_final","metadata":{"execution":{"iopub.status.busy":"2023-05-30T09:59:41.692168Z","iopub.execute_input":"2023-05-30T09:59:41.692576Z","iopub.status.idle":"2023-05-30T09:59:41.707444Z","shell.execute_reply.started":"2023-05-30T09:59:41.692538Z","shell.execute_reply":"2023-05-30T09:59:41.706143Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix,classification_report\nimport seaborn as sns\ncm=confusion_matrix(ytest,y_pred_final)\nax=sns.heatmap(cm,cmap='Blues',annot=True,fmt=' ')\nax.set_title('Confusion Matrix')\nax.set_xlabel('Y Test')\nax.set_ylabel('Y Pred')","metadata":{"execution":{"iopub.status.busy":"2023-05-30T10:32:47.719644Z","iopub.execute_input":"2023-05-30T10:32:47.722362Z","iopub.status.idle":"2023-05-30T10:32:48.592443Z","shell.execute_reply.started":"2023-05-30T10:32:47.722277Z","shell.execute_reply":"2023-05-30T10:32:48.591137Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### modeling-tried but didn't get good accuracy","metadata":{}},{"cell_type":"code","source":"# Naive Bayes \nfrom sklearn.naive_bayes import GaussianNB\nclf = GaussianNB()\n\nclf.fit(xtrain_tfidf, ytrain)\n\npredicted_naive = clf.predict(xtest_tfidf)","metadata":{"execution":{"iopub.status.busy":"2023-05-23T12:49:23.717466Z","iopub.execute_input":"2023-05-23T12:49:23.717827Z","iopub.status.idle":"2023-05-23T12:49:39.766891Z","shell.execute_reply.started":"2023-05-23T12:49:23.717798Z","shell.execute_reply":"2023-05-23T12:49:39.765898Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Metrics :) \nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix \n\nprint('Accuracy Score \\n',accuracy_score(predicted_naive, ytest))\nprint('Confusion Matrix \\n', confusion_matrix(predicted_naive, ytest))\nprint('Classification Report \\n', classification_report(predicted_naive, ytest))","metadata":{"execution":{"iopub.status.busy":"2023-05-23T11:07:38.868305Z","iopub.execute_input":"2023-05-23T11:07:38.868710Z","iopub.status.idle":"2023-05-23T11:07:38.930650Z","shell.execute_reply.started":"2023-05-23T11:07:38.868678Z","shell.execute_reply":"2023-05-23T11:07:38.929524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# MLP classifier \nfrom sklearn.neural_network import MLPClassifier\n\nmlp_cv=MLPClassifier(early_stopping=True, verbose=2)\nmlp_cv.fit(xtrain_tfidf, ytrain)","metadata":{"execution":{"iopub.status.busy":"2023-05-23T11:08:03.273814Z","iopub.execute_input":"2023-05-23T11:08:03.274206Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predicted_mlp = mlp_cv.predict(xtest_tfidf)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Metrics :) \nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix \n\ndef metrics(predicted): \n    predicted_naive = predicted \n    print('Accuracy Score \\n',accuracy_score(predicted_naive, ytest))\n    print('Confusion Matrix \\n', confusion_matrix(predicted_naive, ytest))\n    print('Classification Report \\n', classification_report(predicted_naive, ytest))","metadata":{"execution":{"iopub.status.busy":"2023-05-24T07:31:27.657866Z","iopub.execute_input":"2023-05-24T07:31:27.658421Z","iopub.status.idle":"2023-05-24T07:31:27.666513Z","shell.execute_reply.started":"2023-05-24T07:31:27.658383Z","shell.execute_reply":"2023-05-24T07:31:27.665409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.ensemble import RandomForestClassifier\nrf = RandomForestClassifier()\nrf.fit(xtrain_tfidf, ytrain)\npredictions = rf.predict(xtest_tfidf)\nmetrics(predictions)","metadata":{"execution":{"iopub.status.busy":"2023-05-24T05:23:35.886767Z","iopub.execute_input":"2023-05-24T05:23:35.887153Z","iopub.status.idle":"2023-05-24T05:27:40.187742Z","shell.execute_reply.started":"2023-05-24T05:23:35.887124Z","shell.execute_reply":"2023-05-24T05:27:40.186742Z"},"trusted":true},"execution_count":null,"outputs":[]}]}