{"cells":[{"metadata":{},"cell_type":"markdown","source":"1st step: Loading of the libraries and listing all of the files in the input directory. \n\nFiles you should see are: \n\n/kaggle/input/riiid-test-answer-prediction/example_test.csv\n/kaggle/input/riiid-test-answer-prediction/lectures.csv\n/kaggle/input/riiid-test-answer-prediction/example_sample_submission.csv\n/kaggle/input/riiid-test-answer-prediction/questions.csv\n/kaggle/input/riiid-test-answer-prediction/train.csv\n/kaggle/input/riiid-test-answer-prediction/riiideducation/competition.cpython-37m-x86_64-linux-gnu.so\n/kaggle/input/riiid-test-answer-prediction/riiideducation/__init__.py"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport sklearn as sk\nimport riiideducation # feather dataset \nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":" #used to make feather files easier to load.\n #dtypes = {\n #    \"row_id\": \"int64\",\n #    \"timestamp\": \"int64\",\n #    \"user_id\": \"int32\",\n #    \"content_id\": \"int16\",\n #   \"content_type_id\": \"boolean\",\n #   \"task_container_id\": \"int16\",\n #   \"user_answer\": \"int8\",\n #   \"answered_correctly\": \"int8\",\n #   \"prior_question_elapsed_time\": \"float32\", \n #   \"prior_question_had_explanation\": \"boolean\"\n #}\n\n #files = ['train', 'questions', 'lectures', 'example_test', 'example_sample_submission']\n\n #for file in files:\n #    if file=='train':\n #        data = pd.read_csv(\"../input/riiid-test-answer-prediction/{0}.csv\".format(file), dtype=dtypes)\n #    else:\n #        data = pd.read_csv(\"../input/riiid-test-answer-prediction/{0}.csv\".format(file))\n #    data.to_feather(\"{0}.feather\".format(file))\n #    print(\"File: {0} - size: {1}\".format(file,data.shape))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"2nd Step: Read the train.csv file and generate a table. "},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"# train_dataframe = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/train.csv', low_memory=False, nrows=10**5,)\n# questions_dataframe = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/questions.csv', low_memory=False, nrows=10**5,)\n# example_test = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/example_test.csv', low_memory=False, nrows=10**5,)\n\ntrain_dataframe = pd.read_feather('../input/feathers/train.feather')\nquestions_dataframe = pd.read_feather('../input/feathers/questions.feather')\nlectures = pd.read_feather('../input/feathers/lectures.feather')\nexample_test = pd.read_feather('../input/feathers/example_test.feather')\nexample_sample_submission = pd.read_feather('../input/feathers/example_sample_submission.feather')\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":""},{"metadata":{"trusted":true},"cell_type":"code","source":"#train_dataframe = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/train.csv',usecols = ['user_id','content_id','answered_correctly','content_type_id'])\ntrain_dataframe.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# questions_dataframe = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/questions.csv')\n# example_test = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/example_test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"questions_dataframe.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"3rd Step: Print the user_id values deriving from the train.csv file below. "},{"metadata":{"trusted":true},"cell_type":"code","source":"print(train_dataframe['user_id'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Step 4: Return the table with only columns Content_Id and Answered_Correctly is visible\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"#trainWhereContentIdIsZero = train_dataframe[train_dataframe.content_type_id==0]\n\n#print(trainWhereContentIdIsZero)\n\n#trainDFWithContentIdAndAnsweredCorrectly = trainWhereContentIdIsZero[['content_id','answered_correctly']].groupby('content_id')\n\n# Question I have is grouping by ContentId even necessary? We already filtered the train_dataframe to \n# only show where the Content_Type_Id is equal to Zero so this may not even be needed. (N.I.)\n\n# Did you want to group by the answered correctly values instead? (N.I.)\n\n\n# This will print the first values in each group \n#trainDFWithContentIdAndAnsweredCorrectly.first()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\ndef prepare_features(col_name):\n    df = train_dataframe[train_dataframe.content_type_id==0][[col_name,'answered_correctly']].groupby(col_name).agg(['count','sum'])\n    df.columns=['total', 'positive']\n    df = df.astype('uint64')\n    df['negative'] = df['total']-df['positive']\n    return df\n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"questions_dataframe = prepare_features('content_id')\nquestions_dataframe","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataframe = prepare_features('prior_question_had_explanation')\ntrain_dataframe","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataframe.content_id.unique()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Step 5: Group the train data frame by user id so we can have an idea how well the student is performing in answering the questions correctly. "},{"metadata":{"trusted":true},"cell_type":"code","source":"users_dataframe = prepare_features('user_id')\nusers_dataframe.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Step 6: Create the model (Naive Bayes) "},{"metadata":{"trusted":true},"cell_type":"code","source":"class NaiveBayes:\n    def __init__(self, features, threshold=20):\n        assert type(features)==dict, 'parameter features is not a dictionary!'\n        for f in features.keys():\n            assert type(features[f])==pd.core.frame.DataFrame, 'Wrong datatype for {0}. Each entry of the dictionary must contain a pandas DataFrame'.format(f)\n            assert list(features[f].columns)==['total', 'positive', 'negative'], 'wrong columns in {0} DataFrame'.format(f)\n        self.THRESHOLD = threshold\n        self.features = features\n        self.prior_probability = {}\n        one_feature = list(features.keys())[0]\n        self.prior_probability['negative'] = features[one_feature]['negative'].sum()/features[one_feature]['total'].sum()\n        self.prior_probability['positive'] = features[one_feature]['positive'].sum()/features[one_feature]['total'].sum()\n        \n    def predict(self, data):\n        assert data.keys()==self.features.keys(), \"Keys doesn't match!\"\n        data_len = len(data[list(data.keys())[0]])\n        # pos and neg are the priors for positive and negative classes\n        pos = np.array([self.prior_probability['positive'] for _ in range(data_len)])\n        neg = np.array([self.prior_probability['negative'] for _ in range(data_len)])\n        # multiply the prior probability by the likelihood of each feature\n        for d in data.keys():\n            feature = pd.DataFrame({'id':data[d]})\n            counts=pd.merge(feature,self.features[d],left_on='id',right_index=True,how='left').fillna(0).astype('uint64').values\n            # counts.shape == (sample_len,4)\n            # counts[:,0]==id ; counts[:,1]==total ; counts[:,2]==positive ; counts[:,3]==negative\n            # e.g.: counts == array([[115,46,32,14],[124,10,7,3],[115,46,32,14]],dtype=uint64)\n            updatable = np.where(counts[:,1]>self.THRESHOLD)[0]\n            # e.g.: updatable == array([True,False,True])\n            pos[updatable] *= counts[updatable,2]/counts[updatable,1]\n            neg[updatable] *= counts[updatable,3]/counts[updatable,1]\n        return pos/(pos+neg)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"naivebayes = NaiveBayes({'questions': questions_dataframe, 'users':users_dataframe})","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Step 7: Conduct predictions on the example_test dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_questions = example_test['content_id']\ntest_users = example_test['user_id']\ntest_rowids = example_test['row_id']\n\nanswered_correctly = naivebayes.predict({'questions':test_questions, 'users':test_users})\nprediction = pd.DataFrame({'row_id':test_rowids, 'answered_correctly': answered_correctly})\n\nprediction","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Step 8: Prepare submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"env = riiideducation.make_env()\niter_test = env.iter_test()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for (test_df, sample_prediction_df) in iter_test:\n    test_questions = test_df['content_id']\n    test_users = test_df['user_id']\n    answered_correctly = naivebayes.predict({'questions':test_questions, 'users':test_users})\n    test_df['answered_correctly'] = answered_correctly\n    env.predict(test_df.loc[test_df['content_type_id']==0,['row_id','answered_correctly']])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}