{"cells":[
 {
  "cell_type": "code",
  "execution_count": null,
  "metadata": {
   "collapsed": false
  },
  "outputs": [],
  "source": "\nlibrary(data.table)\n\nprint(\"Reading data\")\ntrain <- fread('../input/train.csv' )\n\ntest <- fread('../input/test.csv')\n\nprint(\"Computing means\")\n#transform target variable to log(1 + demand) - this makes sense since we're \n#trying to minimize rmsle and the mean minimizes rmse:\ntrain$log_demand = log1p(train$Demanda_uni_equil) \nmean_total <- mean(train$log_demand) #overall mean\n\n#mean by product\nmean_P <-  train[, .(MP = mean(log_demand)), by = .(Producto_ID)]\n#mean by ruta\nmean_C <-  train[, .(MC = mean(log_demand)), by = .(Cliente_ID)]\n#mean by product and agencia\nmean_PA <- train[, .(MPA = mean(log_demand)), by = .(Producto_ID, Agencia_ID)] \n#mean by product and ruta\nmean_PR <- train[, .(MPR = mean(log_demand)), by = .(Producto_ID, Ruta_SAK)] \n#mean by product, client, agencia\nmean_PCA <- train[, .(MPCA = mean(log_demand)), by = .(Producto_ID, Cliente_ID, Agencia_ID)]\n\n\n"
 },
 {
  "cell_type": "code",
  "execution_count": null,
  "metadata": {
   "collapsed": false
  },
  "outputs": [],
  "source": "head(train)"
 },
 {
  "cell_type": "code",
  "execution_count": null,
  "metadata": {
   "collapsed": false
  },
  "outputs": [],
  "source": "print(\"Merging means with test set\")\nsubmit <- merge(test, mean_PCA, all.x = TRUE, by = c(\"Producto_ID\", \"Cliente_ID\", \"Agencia_ID\"))\nsubmit <- merge(submit, mean_PR, all.x = TRUE, by = c(\"Producto_ID\", \"Ruta_SAK\"))\nsubmit <- merge(submit, mean_PA, all.x = TRUE, by = c(\"Producto_ID\", \"Agencia_ID\"))\nsubmit <- merge(submit, mean_C, all.x = TRUE, by = \"Cliente_ID\")\nsubmit <- merge(submit, mean_P, all.x = TRUE, by = \"Producto_ID\")\n\n# Now create Predictions column;\nsubmit$Pred <- expm1(submit$MPCA)*0.7199+expm1(submit$MPR)*0.1938+0.0978\nsubmit[is.na(Pred)]$Pred <- expm1(submit[is.na(Pred)]$MPR)*0.748+0.169\nsubmit[is.na(Pred)]$Pred <- expm1(submit[is.na(Pred)]$MC)*0.82+0.86\nsubmit[is.na(Pred)]$Pred <- expm1(submit[is.na(Pred)]$MPA)*0.54+0.8\nsubmit[is.na(Pred)]$Pred <- expm1(submit[is.na(Pred)]$MP)*0.47+1.03\nsubmit[is.na(Pred)]$Pred <- expm1(mean_total)\n\nsubmit$Pred <- round(submit$Pred,3)\n\nprint(\"Write out submission file\")\n# now relabel columns ready for creatig submission\nsetnames(submit,\"Pred\",\"Demanda_uni_equil\")\n# Any results you write to the current directory are saved as output.\nwrite.csv(submit[,.(id,Demanda_uni_equil)],\"submit_mean_by_Agency_Ruta_Client.csv\", row.names = FALSE)\nprint(\"Done!\")"
 }
],"metadata":{"kernelspec":{"display_name":"R","language":"R","name":"ir"}}, "nbformat": 4, "nbformat_minor": 0}