{
  "id": 22227,
  "title": "Feature hashing trick with partial fitting (low memore usage)",
  "url": "/competitions/grupo-bimbo-inventory-demand/discussion/22227",
  "author_name": "Insaf Ashrapov",
  "post_date": "2016-07-13T12:38:44.027000",
  "votes": 9,
  "comment_count": 0,
  "views": 716,
  "content": "<p>We keeping in mind, there are mostly categorical values with such unique numbers of them:</p>\n\n<pre><code>train.csv \nAgencia_ID: # of unique = 552 \nCanal_ID: # of unique = 9\nRuta_SAK: # of unique = 3603 \nCliente_ID: # of unique = 880604\nProducto_ID: # of unique = 1799\n</code></pre>\n\n<p><strong>Demanda_uni_equil</strong>  will be used as a target. We will iterate through the file to be able to store all data in the memory.</p>\n\n<p>Due to the fact, that there are a lot  clients, that column will droped.</p>\n\n<pre><code>import numpy as np\nimport pandas as pd\nimport math\nimport sklearn\n\nfrom sklearn.cross_validation import cross_val_score\nfrom subprocess import check_output\n\nfrom sklearn.metrics import make_scorer, mean_squared_error\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.preprocessing import normalize\n\nfrom sklearn.linear_model import SGDRegressor\n\nfrom sklearn.preprocessing import OneHotEncoder\n\n #   rmsle - error function used in LB\n    def rmsle_func(actual, predicted):\n        return np.sqrt(msle(actual, predicted))\n    def msle(actual, predicted):\n        return np.mean(sle(actual, predicted))\n    def sle(actual, predicted):\n        return (np.power(np.log(np.array(actual)+1) - \n                np.log(np.array(predicted)+1), 2))\n# to create post only non negative values\n    def nonnegative(x):\n        if x &gt; 0:\n            return x\n        else: \n            return 0\n\n#  to decrease memory usage:          \ndtypes = {'Semana' : 'int32',\n                              'Agencia_ID' :'int32',\n                              'Canal_ID' : 'int32',\n                              'Ruta_SAK' : 'int32',\n                              'Cliente-ID' : 'int32',\n                              'Producto_ID':'int32',\n                              'Venta_hoy':'float32',\n                              'Venta_uni_hoy': 'int32',\n                              'Dev_uni_proxima':'int32',\n                              'Dev_proxima':'float32',\n                              'Demanda_uni_equil':'int32'}\n\nmodel = SGDRegressor(loss='squared_loss', penalty='l2', alpha=0.0001, \n                     fit_intercept=True, n_iter=10, shuffle=True, verbose=0, \n                     epsilon=0.1, learning_rate='invscaling', \n                     eta0=0.01, power_t=0.25, warm_start=True, average=False)\n\nfrom sklearn.feature_extraction import FeatureHasher\nh = FeatureHasher(n_features=8000, input_type = 'string') #8000 - the number of total unique values over all data\n\n\ndf_train = pd.read_csv('train.csv', dtype  = dtypes, usecols=[&quot;Semana&quot;, &quot;Agencia_ID&quot;, &quot;Canal_ID&quot;, 'Ruta_SAK',\n                                                             'Producto_ID','Demanda_uni_equil'], chunksize=1500)\n\n# use astype('str')  in python 3\ni = 1\nnum = 100# to limit train size\n#pd.concat([train, pd.get_dummies(train['Semana'],sparse=True)], axis=1, join_axes=[train.index])\nfor chunk in df_train:\n    if  i &lt; num :\n        X_chunk = h.fit_transform(chunk[[&quot;Semana&quot;, &quot;Agencia_ID&quot;, &quot;Canal_ID&quot;, 'Ruta_SAK', 'Producto_ID']].astype('string').as_matrix())\n        y_chunk = np.ravel(chunk[['Demanda_uni_equil']].as_matrix())\n\n        model.partial_fit(X_chunk, y_chunk)\n        i = i + 1\n    elif i == num:\n        X_chunk = h.fit_transform(chunk[[&quot;Semana&quot;, &quot;Agencia_ID&quot;, &quot;Canal_ID&quot;, 'Ruta_SAK','Producto_ID']].astype('string').values)\n        y_chunk = np.ravel(chunk[['Demanda_uni_equil']].values)\n\n        print ('rmsle: ', rmsle_func(y_chunk, model.predict(X_chunk)))\n        print ('RMSE ', math.sqrt(sklearn.metrics.mean_squared_error(y_chunk, model.predict(X_chunk))))\n        i = i + 1\n    else:\n        break\nprint 'Finished the fitting'\n\n#predict\n\n    X_test = pd.read_csv('../input/test.csv',dtype  = dtypes,usecols=['id', &quot;Semana&quot;, &quot;Agencia_ID&quot;, &quot;Canal_ID&quot;, 'Ruta_SAK',\n                                                            'Producto_ID'])\nids = X_test['id']\nX_test.drop(['id'], axis =1, inplace = True)\n\ny_predicted = model.predict(h.fit_transform(X_test.astype('string').values))\n\n\n\n# submission   \nsubmission = pd.DataFrame({&quot;id&quot;:ids, &quot;Demanda_uni_equil&quot;: y_predicted})\n\ny_predicted = map(nonnegative, y_predicted)\n\nsubmission = pd.DataFrame({&quot;id&quot;:ids, &quot;Demanda_uni_equil&quot;: y_predicted})\ncols = ['id',&quot;Demanda_uni_equil&quot;]\nsubmission = submission[cols]\nsubmission.to_csv(&quot;submission.csv&quot;, index=False)\n\n\nprint('Completed!')\n</code></pre>",
  "messages": [
    {
      "id": 127129,
      "postDate": "2016-07-13T12:38:44.027Z",
      "content": "<p>We keeping in mind, there are mostly categorical values with such unique numbers of them:</p>\n\n<pre><code>train.csv \nAgencia_ID: # of unique = 552 \nCanal_ID: # of unique = 9\nRuta_SAK: # of unique = 3603 \nCliente_ID: # of unique = 880604\nProducto_ID: # of unique = 1799\n</code></pre>\n\n<p><strong>Demanda_uni_equil</strong>  will be used as a target. We will iterate through the file to be able to store all data in the memory.</p>\n\n<p>Due to the fact, that there are a lot  clients, that column will droped.</p>\n\n<pre><code>import numpy as np\nimport pandas as pd\nimport math\nimport sklearn\n\nfrom sklearn.cross_validation import cross_val_score\nfrom subprocess import check_output\n\nfrom sklearn.metrics import make_scorer, mean_squared_error\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.preprocessing import normalize\n\nfrom sklearn.linear_model import SGDRegressor\n\nfrom sklearn.preprocessing import OneHotEncoder\n\n #   rmsle - error function used in LB\n    def rmsle_func(actual, predicted):\n        return np.sqrt(msle(actual, predicted))\n    def msle(actual, predicted):\n        return np.mean(sle(actual, predicted))\n    def sle(actual, predicted):\n        return (np.power(np.log(np.array(actual)+1) - \n                np.log(np.array(predicted)+1), 2))\n# to create post only non negative values\n    def nonnegative(x):\n        if x &gt; 0:\n            return x\n        else: \n            return 0\n\n#  to decrease memory usage:          \ndtypes = {'Semana' : 'int32',\n                              'Agencia_ID' :'int32',\n                              'Canal_ID' : 'int32',\n                              'Ruta_SAK' : 'int32',\n                              'Cliente-ID' : 'int32',\n                              'Producto_ID':'int32',\n                              'Venta_hoy':'float32',\n                              'Venta_uni_hoy': 'int32',\n                              'Dev_uni_proxima':'int32',\n                              'Dev_proxima':'float32',\n                              'Demanda_uni_equil':'int32'}\n\nmodel = SGDRegressor(loss='squared_loss', penalty='l2', alpha=0.0001, \n                     fit_intercept=True, n_iter=10, shuffle=True, verbose=0, \n                     epsilon=0.1, learning_rate='invscaling', \n                     eta0=0.01, power_t=0.25, warm_start=True, average=False)\n\nfrom sklearn.feature_extraction import FeatureHasher\nh = FeatureHasher(n_features=8000, input_type = 'string') #8000 - the number of total unique values over all data\n\n\ndf_train = pd.read_csv('train.csv', dtype  = dtypes, usecols=[&quot;Semana&quot;, &quot;Agencia_ID&quot;, &quot;Canal_ID&quot;, 'Ruta_SAK',\n                                                             'Producto_ID','Demanda_uni_equil'], chunksize=1500)\n\n# use astype('str')  in python 3\ni = 1\nnum = 100# to limit train size\n#pd.concat([train, pd.get_dummies(train['Semana'],sparse=True)], axis=1, join_axes=[train.index])\nfor chunk in df_train:\n    if  i &lt; num :\n        X_chunk = h.fit_transform(chunk[[&quot;Semana&quot;, &quot;Agencia_ID&quot;, &quot;Canal_ID&quot;, 'Ruta_SAK', 'Producto_ID']].astype('string').as_matrix())\n        y_chunk = np.ravel(chunk[['Demanda_uni_equil']].as_matrix())\n\n        model.partial_fit(X_chunk, y_chunk)\n        i = i + 1\n    elif i == num:\n        X_chunk = h.fit_transform(chunk[[&quot;Semana&quot;, &quot;Agencia_ID&quot;, &quot;Canal_ID&quot;, 'Ruta_SAK','Producto_ID']].astype('string').values)\n        y_chunk = np.ravel(chunk[['Demanda_uni_equil']].values)\n\n        print ('rmsle: ', rmsle_func(y_chunk, model.predict(X_chunk)))\n        print ('RMSE ', math.sqrt(sklearn.metrics.mean_squared_error(y_chunk, model.predict(X_chunk))))\n        i = i + 1\n    else:\n        break\nprint 'Finished the fitting'\n\n#predict\n\n    X_test = pd.read_csv('../input/test.csv',dtype  = dtypes,usecols=['id', &quot;Semana&quot;, &quot;Agencia_ID&quot;, &quot;Canal_ID&quot;, 'Ruta_SAK',\n                                                            'Producto_ID'])\nids = X_test['id']\nX_test.drop(['id'], axis =1, inplace = True)\n\ny_predicted = model.predict(h.fit_transform(X_test.astype('string').values))\n\n\n\n# submission   \nsubmission = pd.DataFrame({&quot;id&quot;:ids, &quot;Demanda_uni_equil&quot;: y_predicted})\n\ny_predicted = map(nonnegative, y_predicted)\n\nsubmission = pd.DataFrame({&quot;id&quot;:ids, &quot;Demanda_uni_equil&quot;: y_predicted})\ncols = ['id',&quot;Demanda_uni_equil&quot;]\nsubmission = submission[cols]\nsubmission.to_csv(&quot;submission.csv&quot;, index=False)\n\n\nprint('Completed!')\n</code></pre>",
      "rawMarkdown": "We keeping in mind, there are mostly categorical values with such unique numbers of them:\r\n\r\n    train.csv \r\n    Agencia_ID: # of unique = 552 \r\n    Canal_ID: # of unique = 9\r\n    Ruta_SAK: # of unique = 3603 \r\n    Cliente_ID: # of unique = 880604\r\n    Producto_ID: # of unique = 1799\r\n\r\n**Demanda_uni_equil**  will be used as a target. We will iterate through the file to be able to store all data in the memory.\r\n\r\nDue to the fact, that there are a lot  clients, that column will droped.\r\n\r\n\r\n    import numpy as np\r\n    import pandas as pd\r\n    import math\r\n    import sklearn\r\n    \r\n    from sklearn.cross_validation import cross_val_score\r\n    from subprocess import check_output\r\n    \r\n    from sklearn.metrics import make_scorer, mean_squared_error\r\n    from sklearn.cross_validation import train_test_split\r\n    from sklearn.preprocessing import normalize\r\n    \r\n    from sklearn.linear_model import SGDRegressor\r\n    \r\n    from sklearn.preprocessing import OneHotEncoder\r\n    \r\n     #   rmsle - error function used in LB\r\n        def rmsle_func(actual, predicted):\r\n            return np.sqrt(msle(actual, predicted))\r\n        def msle(actual, predicted):\r\n            return np.mean(sle(actual, predicted))\r\n        def sle(actual, predicted):\r\n            return (np.power(np.log(np.array(actual)+1) - \r\n                    np.log(np.array(predicted)+1), 2))\r\n    # to create post only non negative values\r\n        def nonnegative(x):\r\n            if x > 0:\r\n                return x\r\n            else: \r\n                return 0\r\n     \r\n    #  to decrease memory usage:          \r\n    dtypes = {'Semana' : 'int32',\r\n                                  'Agencia_ID' :'int32',\r\n                                  'Canal_ID' : 'int32',\r\n                                  'Ruta_SAK' : 'int32',\r\n                                  'Cliente-ID' : 'int32',\r\n                                  'Producto_ID':'int32',\r\n                                  'Venta_hoy':'float32',\r\n                                  'Venta_uni_hoy': 'int32',\r\n                                  'Dev_uni_proxima':'int32',\r\n                                  'Dev_proxima':'float32',\r\n                                  'Demanda_uni_equil':'int32'}\r\n    \r\n    model = SGDRegressor(loss='squared_loss', penalty='l2', alpha=0.0001, \r\n                         fit_intercept=True, n_iter=10, shuffle=True, verbose=0, \r\n                         epsilon=0.1, learning_rate='invscaling', \r\n                         eta0=0.01, power_t=0.25, warm_start=True, average=False)\r\n    \r\n    from sklearn.feature_extraction import FeatureHasher\r\n    h = FeatureHasher(n_features=8000, input_type = 'string') #8000 - the number of total unique values over all data\r\n\r\n\r\n    df_train = pd.read_csv('train.csv', dtype  = dtypes, usecols=[\"Semana\", \"Agencia_ID\", \"Canal_ID\", 'Ruta_SAK',\r\n                                                                 'Producto_ID','Demanda_uni_equil'], chunksize=1500)\r\n    \r\n    # use astype('str')  in python 3\r\n    i = 1\r\n    num = 100# to limit train size\r\n    #pd.concat([train, pd.get_dummies(train['Semana'],sparse=True)], axis=1, join_axes=[train.index])\r\n    for chunk in df_train:\r\n        if  i < num :\r\n            X_chunk = h.fit_transform(chunk[[\"Semana\", \"Agencia_ID\", \"Canal_ID\", 'Ruta_SAK', 'Producto_ID']].astype('string').as_matrix())\r\n            y_chunk = np.ravel(chunk[['Demanda_uni_equil']].as_matrix())\r\n            \r\n            model.partial_fit(X_chunk, y_chunk)\r\n            i = i + 1\r\n        elif i == num:\r\n            X_chunk = h.fit_transform(chunk[[\"Semana\", \"Agencia_ID\", \"Canal_ID\", 'Ruta_SAK','Producto_ID']].astype('string').values)\r\n            y_chunk = np.ravel(chunk[['Demanda_uni_equil']].values)\r\n            \r\n            print ('rmsle: ', rmsle_func(y_chunk, model.predict(X_chunk)))\r\n            print ('RMSE ', math.sqrt(sklearn.metrics.mean_squared_error(y_chunk, model.predict(X_chunk))))\r\n            i = i + 1\r\n        else:\r\n            break\r\n    print 'Finished the fitting'\r\n\r\n    #predict\r\n    \r\n        X_test = pd.read_csv('../input/test.csv',dtype  = dtypes,usecols=['id', \"Semana\", \"Agencia_ID\", \"Canal_ID\", 'Ruta_SAK',\r\n                                                                'Producto_ID'])\r\n    ids = X_test['id']\r\n    X_test.drop(['id'], axis =1, inplace = True)\r\n    \r\n    y_predicted = model.predict(h.fit_transform(X_test.astype('string').values))\r\n\r\n         \r\n\r\n    # submission   \r\n    submission = pd.DataFrame({\"id\":ids, \"Demanda_uni_equil\": y_predicted})\r\n    \r\n    y_predicted = map(nonnegative, y_predicted)\r\n    \r\n    submission = pd.DataFrame({\"id\":ids, \"Demanda_uni_equil\": y_predicted})\r\n    cols = ['id',\"Demanda_uni_equil\"]\r\n    submission = submission[cols]\r\n    submission.to_csv(\"submission.csv\", index=False)\r\n    \r\n    \r\n    print('Completed!')",
      "votes": 8
    }
  ],
  "comments": [],
  "raw_markdown_by_id": {
    "127129": "We keeping in mind, there are mostly categorical values with such unique numbers of them:\r\n\r\n    train.csv \r\n    Agencia_ID: # of unique = 552 \r\n    Canal_ID: # of unique = 9\r\n    Ruta_SAK: # of unique = 3603 \r\n    Cliente_ID: # of unique = 880604\r\n    Producto_ID: # of unique = 1799\r\n\r\n**Demanda_uni_equil**  will be used as a target. We will iterate through the file to be able to store all data in the memory.\r\n\r\nDue to the fact, that there are a lot  clients, that column will droped.\r\n\r\n\r\n    import numpy as np\r\n    import pandas as pd\r\n    import math\r\n    import sklearn\r\n    \r\n    from sklearn.cross_validation import cross_val_score\r\n    from subprocess import check_output\r\n    \r\n    from sklearn.metrics import make_scorer, mean_squared_error\r\n    from sklearn.cross_validation import train_test_split\r\n    from sklearn.preprocessing import normalize\r\n    \r\n    from sklearn.linear_model import SGDRegressor\r\n    \r\n    from sklearn.preprocessing import OneHotEncoder\r\n    \r\n     #   rmsle - error function used in LB\r\n        def rmsle_func(actual, predicted):\r\n            return np.sqrt(msle(actual, predicted))\r\n        def msle(actual, predicted):\r\n            return np.mean(sle(actual, predicted))\r\n        def sle(actual, predicted):\r\n            return (np.power(np.log(np.array(actual)+1) - \r\n                    np.log(np.array(predicted)+1), 2))\r\n    # to create post only non negative values\r\n        def nonnegative(x):\r\n            if x > 0:\r\n                return x\r\n            else: \r\n                return 0\r\n     \r\n    #  to decrease memory usage:          \r\n    dtypes = {'Semana' : 'int32',\r\n                                  'Agencia_ID' :'int32',\r\n                                  'Canal_ID' : 'int32',\r\n                                  'Ruta_SAK' : 'int32',\r\n                                  'Cliente-ID' : 'int32',\r\n                                  'Producto_ID':'int32',\r\n                                  'Venta_hoy':'float32',\r\n                                  'Venta_uni_hoy': 'int32',\r\n                                  'Dev_uni_proxima':'int32',\r\n                                  'Dev_proxima':'float32',\r\n                                  'Demanda_uni_equil':'int32'}\r\n    \r\n    model = SGDRegressor(loss='squared_loss', penalty='l2', alpha=0.0001, \r\n                         fit_intercept=True, n_iter=10, shuffle=True, verbose=0, \r\n                         epsilon=0.1, learning_rate='invscaling', \r\n                         eta0=0.01, power_t=0.25, warm_start=True, average=False)\r\n    \r\n    from sklearn.feature_extraction import FeatureHasher\r\n    h = FeatureHasher(n_features=8000, input_type = 'string') #8000 - the number of total unique values over all data\r\n\r\n\r\n    df_train = pd.read_csv('train.csv', dtype  = dtypes, usecols=[\"Semana\", \"Agencia_ID\", \"Canal_ID\", 'Ruta_SAK',\r\n                                                                 'Producto_ID','Demanda_uni_equil'], chunksize=1500)\r\n    \r\n    # use astype('str')  in python 3\r\n    i = 1\r\n    num = 100# to limit train size\r\n    #pd.concat([train, pd.get_dummies(train['Semana'],sparse=True)], axis=1, join_axes=[train.index])\r\n    for chunk in df_train:\r\n        if  i < num :\r\n            X_chunk = h.fit_transform(chunk[[\"Semana\", \"Agencia_ID\", \"Canal_ID\", 'Ruta_SAK', 'Producto_ID']].astype('string').as_matrix())\r\n            y_chunk = np.ravel(chunk[['Demanda_uni_equil']].as_matrix())\r\n            \r\n            model.partial_fit(X_chunk, y_chunk)\r\n            i = i + 1\r\n        elif i == num:\r\n            X_chunk = h.fit_transform(chunk[[\"Semana\", \"Agencia_ID\", \"Canal_ID\", 'Ruta_SAK','Producto_ID']].astype('string').values)\r\n            y_chunk = np.ravel(chunk[['Demanda_uni_equil']].values)\r\n            \r\n            print ('rmsle: ', rmsle_func(y_chunk, model.predict(X_chunk)))\r\n            print ('RMSE ', math.sqrt(sklearn.metrics.mean_squared_error(y_chunk, model.predict(X_chunk))))\r\n            i = i + 1\r\n        else:\r\n            break\r\n    print 'Finished the fitting'\r\n\r\n    #predict\r\n    \r\n        X_test = pd.read_csv('../input/test.csv',dtype  = dtypes,usecols=['id', \"Semana\", \"Agencia_ID\", \"Canal_ID\", 'Ruta_SAK',\r\n                                                                'Producto_ID'])\r\n    ids = X_test['id']\r\n    X_test.drop(['id'], axis =1, inplace = True)\r\n    \r\n    y_predicted = model.predict(h.fit_transform(X_test.astype('string').values))\r\n\r\n         \r\n\r\n    # submission   \r\n    submission = pd.DataFrame({\"id\":ids, \"Demanda_uni_equil\": y_predicted})\r\n    \r\n    y_predicted = map(nonnegative, y_predicted)\r\n    \r\n    submission = pd.DataFrame({\"id\":ids, \"Demanda_uni_equil\": y_predicted})\r\n    cols = ['id',\"Demanda_uni_equil\"]\r\n    submission = submission[cols]\r\n    submission.to_csv(\"submission.csv\", index=False)\r\n    \r\n    \r\n    print('Completed!')"
  }
}